UIAlertController添加输入框并监听输入内容控制按钮是否可点击

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    
    __weak UIAlertController * alertC = [UIAlertController alertControllerWithTitle:@"请输入密码" message:@"输入提示" preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction * action_cancle = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    
    UIAlertAction * action_sure = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        // 移除监听
        [[NSNotificationCenter defaultCenter] removeObserver:self name:UITextFieldTextDidChangeNotification object:nil];
        // 获取输入内容
        UITextField *tf = [[alertC textFields] objectAtIndex:0];
        NSLog(@"%@", tf.text);
    }];
    
    [alertC addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        
        textField.keyboardType = UIKeyboardTypeNumberPad;
        // 添加监听
        [[NSNotificationCenter defaultCenter] addObserverForName:UITextFieldTextDidChangeNotification object:textField queue:[NSOperationQueue currentQueue] usingBlock:^(NSNotification * _Nonnull note) {
            // 设置按钮点击状态
            action_sure.enabled = textField.text.length == 4 ? YES : NO;
        }];
    }];
    
    [alertC addAction:action_cancle];
    [alertC addAction:action_sure];
    action_sure.enabled = NO;
    
    [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:alertC animated:YES completion:nil];
}

你可能感兴趣的:(UIAlertController添加输入框并监听输入内容控制按钮是否可点击)