NSInteger status = [self.bindingStatus integerValue];
    if (status == 1) {//这句判断无关紧要可以去掉
        UIAlertController * alertController = [UIAlertController alertControllerWithTitle:@"立即设置提现密码" message:nil preferredStyle:UIAlertControllerStyleAlert];
        [alertController addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
            textField.placeholder = @"请输入提现密码";
            textField.secureTextEntry = YES;
        }];
        [alertController addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
            textField.placeholder = @"请再次输入密码";
            textField.secureTextEntry = YES;
            [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(alertTextFieldDidChange:) name:UITextFieldTextDidChangeNotification object:textField];
        }];
        //按钮按下时,让程序读取文本框中的值
        UIAlertAction * okAction = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            UITextField * firstPassword = alertController.textFields.firstObject;
            UITextField * confirmPassword = alertController.textFields.lastObject;
            self.firstPassword = firstPassword.text;
            self.confirmPassword = confirmPassword.text;
            [[NSNotificationCenter defaultCenter] removeObserver:self name:UITextFieldTextDidChangeNotification object:nil];
        }];
//        [alertController addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
//            [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(alertTextFieldDidChange:) name:UITextFieldTextDidChangeNotification object:textField];
//        }];
        
        okAction.enabled = NO;
        [alertController addAction:okAction];
        [self presentViewController:alertController animated:YES completion:nil];
        
    }
}

如果我们想要实现UIAlertView中的委托方法alertViewShouldEnableOtherButton:方法的话可能会有一些复杂。假定我们要让“设置提现密码”文本框中至少有3个字符才能激活“确认”按钮。很遗憾的是,在UIAlertController中并没有相应的委托方法,因此我们需要向“设置提现密码”文本框中添加一个Observer。Observer模式定义对象间的一对多的依赖关系,当一个对象的状态发生改变时, 所有依赖于它的对象都得到通知并被自动更新。我们可以在构造代码块中添加如下的代码片段来实现。

-(void)alertTextFieldDidChange:(NSNotification *)notification{
    UIAlertController *alertController = (UIAlertController *)self.presentedViewController;
    if (alertController) {
        UITextField *confirmPassword = alertController.textFields.lastObject;
        UIAlertAction *okAction = alertController.actions.lastObject;
        okAction.enabled = confirmPassword.text.length > 2;
    }
}

图片描述


ShevaKuilin
388 声望32 粉丝

世间好物不坚牢,彩云易碎琉璃脆。