警告框的使用

警告框通常被作为一个代码块使用,一劳永逸,只要写一次以后直接调用代码跨即可。通过一个模拟登陆的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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值