zoukankan      html  css  js  c++  java
  • UIAlertController 自定义输入框及KVO监听 分类: ios技术 2015-01-20 15:33 199人阅读 评论(1) 收藏

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




    版权声明:本文为博主原创文章,未经博主允许不得转载。

  • 相关阅读:
    Linux下如何从mysql数据库里导出导入数据
    安装好Pycharm后如何配置Python解释器简易教程
    Windows离线安装Python第三方库的方法
    时间输入框的测试方法
    doc转html
    pdf转png图片
    html转pdf
    html转pdf
    复习 注解反射
    Mybatis实现插入数据的时候将主键赋值给对象的两种方法
  • 原文地址:https://www.cnblogs.com/liuqixu/p/4684010.html
Copyright © 2011-2022 走看看