UIAlertController(警告栏) 自学之初体验

UIAlertController有两种样式  preferredStyle:数组

UIAlertControllerStyleAlert (位于屏幕的中部)spa

UIAlertControllerStyleActionSheet(位于屏幕的下方)
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"标题" message:@"默罕默德~本拉登" preferredStyle:UIAlertControllerStyleAlert];  //UIAlertController的建立server

UIAlertAction是UIAlertController的按钮样式
title按钮的名称,style按钮的样式,handler处理层序(点击按钮执行的代码)
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消cancel" style:UIAlertActionStyleCancel handler:nil];
    UIAlertAction *defaultAction = [UIAlertAction actionWithTitle:@"默认" style:UIAlertActionStyleDefault handler:nil];
    UIAlertAction *resetAction = [UIAlertAction actionWithTitle:@"重置" style:UIAlertActionStyleDestructive handler:nil];
    //添加按钮到UIAlertController上
    [alert addAction:cancelAction];
    [alert addAction:defaultAction];
    [alert addAction:resetAction];对象

 一、文本输入框只能添加到Alert的风格中,ActionSheet是不容许的;blog

 二、UIAlertController具备只读属性的textFields数组,须要可直接按本身须要的顺序添加;事件

 三、添加方式是使用block,参数是UITextField;get

 四、添加UITextField监听方法和实现方法。it

    //添加文本输入框
    [alert addTextFieldWithConfigurationHandler:^(UITextField *textField){
        textField.placeholder = @"登录";
        //能够为textField添加事件
    }];
    [alert addTextFieldWithConfigurationHandler:^(UITextField *textField){
        textField.placeholder = @"密码";
        textField.secureTextEntry = YES;
        //能够为textField添加事件
    }];io

添加一个事件能够用来输出用户名和密码(textFields是属性,是一个数组)ast

UIAlertAction *getAction = [UIAlertAction actionWithTitle:@"肯定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action){
            UITextField *login = alert.textFields[0];
            UITextField *passWord = alert.textFields[1];
            NSLog(@"登录:%@   密码:%@",login.text,passWord.text);
        }];//获取textField的文本内容
        [alert addAction:getAction];


若是要监听textField开始,结束,改变状态,须要添加监听代码
    [alert addTextFieldWithConfigurationHandler:^(UITextField *textField){
            textField.placeholder = @"添加监听代码";
            [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(alertTextFieldDidChange:) name:UITextFieldTextDidChangeNotification object:textField];
        }];
    [self presentViewController:alert animated:YES completion:^{
    }];  //模态推送到页面上

//监听的方法
-(void)alertTextFieldDidChange:(NSNotification *)notification{
    UIAlertController *alertController = (UIAlertController *)self.presentedViewController;
    if (alertController) {
        //为textFields数组中下标为2的textField为监听对象
        //也是alertController.textFields.lastObject
        UITextField *listen = alertController.textFields[2];
        //限制,若是listen限制输入长度在5个字符内,不然不容许点击默认Defult键
        //当UITextField输入字数超过5个,按钮变灰色,enable为NO
        UIAlertAction *action = alertController.actions.lastObject;
        action.enabled = listen.text.length<=5;
    }

相关文章
相关标签/搜索