您的位置:首页 > 产品设计 > UI/UE

UIAlertController 自定义输入框及KVO监听

2015-07-28 15:36 555 查看
UIAlertController极大的灵活性意味着您不必拘泥于内置样式。以前我们只能在默认视图、文本框视图、密码框视图、登录和密码输入框视图中选择,现在我们可以向对话框中添加任意数目的UITextField对象,并且可以使用所有的UITextField特性。当向对话框控制器中添加文本框时,需要指定一个用来配置文本框的代码块。

UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"文本对话框" message:@"登录和密码" preferredStyle:UIAlertControllerStyleAlert];

[alertController addTextFieldWithConfigurationHandler:^(UITextField *textField){

textField.placeholder = @"登录";

}];

[alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {

textField.placeholder = @"密码";

textField.secureTextEntry = YES;

}];

// 添加一个确定按钮

UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {

UITextField *login = alertController.textFields.firstObject;

UITextField *password = alertController.textFields.lastObject;

}];

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

[alertController addTextFieldWithConfigurationHandler:^(UITextField *textField){

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(alertTextFieldDidChange:) name:UITextFieldTextDidChangeNotification object:textField];

}];

当视图控制器释放的时候我们需要移除这个Observer,我们通过在每个按钮动作的handler代码块(还有其他任何可能释放视图控制器的地方)中添加合适的代码来实现它。比如说在okAction这个按钮动作中:

UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"好的" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {

[[NSNotificationCenter defaultCenter] removeObserver:self name:UITextFieldTextDidChangeNotification object:nil];

}];

在显示对话框之前,我们要冻结“确定”按钮

okAction.enabled = NO;

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


这样只有在“登录”文本框中输入3个以上的字符才能解冻"确定"按钮.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: