zoukankan      html  css  js  c++  java
  • UIAlertController 自定义输入框及KVO监听

    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个以上的字符才能解冻"确定"按钮.

  • 相关阅读:
    jquery防冲突的写法
    easyUI.checkForm
    获取树形节根节点下面所有层级子节点
    自动发布web应用程序或者网站
    MVC UI Jquery
    Linq模糊查询
    常用正则表达式示例
    Easy UI中,当批量操作后,移除总复选框的选中状态
    常用的JS
    检查是否安装或运行了IIS服务
  • 原文地址:https://www.cnblogs.com/liuqixu/p/4682981.html
Copyright © 2011-2022 走看看