警告框的使用

来源:互联网 发布:网络研修中的困惑 编辑:程序博客网 时间:2024/06/05 04:22

警告框通常被作为一个代码块使用,一劳永逸,只要写一次以后直接调用代码跨即可。通过一个模拟登陆的demo,看一下警告框会用到的所用控件。警告框也是一个controller。这点一定要注意

封装显示alert控制器的函数

-(void)showAlertView {    //step1:创建UIAlertController的实例,创建实例时需要制定一个style参数,该参数写成Alert样式,则代表创建的是警告框    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"title" message:@"用户名或密码错误" preferredStyle:UIAlertControllerStyleAlert];    //step2:创建可以收集用户意图的按键 UIAlertAction,创建时,不仅仅说明按键上要显示的提示性文字,还需要使用block的方式来设定点击了该按键之后要做的事情    UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {        //点中按键后 执行的代码        NSLog(@"点中了取消");    }];    UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"重新登录" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {        NSLog(@"重新登录");        //数组中的 文本框 是 第四步 添加进来的文本框        UITextField *usernameField = alert.textFields[0];        UITextField *passwordField = alert.textFields[1];        if ([usernameField.text isEqualToString:@"abc"] &&  [passwordField.text isEqualToString:@"123"]) {            NSLog(@"登录成功");        }else {            NSLog(@"登录失败");            //继续弹对话框  重新输入            [self showAlertView];        }    }];    UIAlertAction *action3 = [UIAlertAction actionWithTitle:@"删除" style:UIAlertActionStyleDestructive handler:nil];    //step3:将AlertAction添加到AlertController中    [alert addAction:action1];    [alert addAction:action2];    [alert addAction:action3];    //step4:(可选) 添加可以输入的文本框    /*参数是 block ,在block中可以设置 alert帮我们创建 文本框*/    [alert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {        textField.placeholder = @"请重新输入用户名";    }];    [alert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {        textField.placeholder = @"请重新输入密码";        textField.secureTextEntry = YES;    }];    //step5:是用控制器的presentViewController方法将AlertController推出显示    [self presentViewController:alert animated:YES completion:nil];}

在touchesBegan事件中添加调用

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {    [self showAlertView];}

大功告成一起去看下效果吧,如果用户名不是abc 密码不是123就会一直弹出警告框让你重新登录,效果如下图:
这里写图片描述

0 0
原创粉丝点击