AlertController提示框

UIAlertController是ios8后新出的提示框,充分整合了UIActionSheet和UIAlertView样式,使得开发更加方便.下面我们将对UIAlertController进行基本的介绍.
创建UIAlertController的方法类似于UIAlertView的创建
oc代码:

/*
UIAlertControllerStyleActionSheet: UIActionSheet样式
UIAlertControllerStyleAlert: UIAlertView样式
*/
UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"消息" message:@"详细信息" preferredStyle:UIAlertControllerStyleAlert];
//显示提示框
[self presentViewController:alert animated:YES completion:nil];

其中,它的preferredStyle可以设置为UIAlertControllerStyleActionSheet或者UIAlertControllerStyleAlert来制定样式.
要显示的控制器中的时候,不像UIAlertView有show的方法,因为UIAlertController创建出来的是一个控制器,所以可以用modal的形式来展示:
UIAlertControllerStyleAlert样式展示效果:
无按钮效果:
无按钮
两个按钮效果:
两个按钮
三个按钮效果:
三个按钮
UIAlertControllerStyleActionSheet样式展示效果:
无按钮效果:
无按钮
两个按钮效果:
两个按钮
三个按钮效果:
三个按钮

往UIAlertController中添加按钮:

/*按钮样式选择:
     UIAlertActionStyleDefault 默认
     UIAlertActionStyleCancel 取消
     UIAlertActionStyleDestructive 确认毁灭性的操作
     */
//添加取消按钮
UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        //具体实现逻辑代码
    }];
    [alert addAction:cancel];
 //添加确定按钮
UIAlertAction *destructive = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        //具体实现逻辑代码
    }];
[alert addAction:destructive];

在UIAlertController中一般还需要用到文本框(例如登录效果)
需要注意的是:UIAlertControllerStyleActionSheet不能有文本框(否则会报: * Terminating app due to uncaught exception ‘NSInternalInconsistencyException’, reason: ‘**Text fields can only be added to an alert controller of style UIAlertControllerStyleAlert‘这个错误)
可以添加文本框的只有UIAlertControllerStyleAlert.
oc代码:

[alert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        //这里详细设置文本框的属性
    }];

效果:
文本框

一旦我们需要拿到用户输入文本框的内容,比如点击确认的时候,获取用户的账号密码,需要通过UIAlertController的按钮来拿到其文本框属性,在其中最需要注意的一点是防止循环引用,例如我们上一篇block循环引用中提到block循环引用原理
具体oc代码为:

//解决循环引用问题
__weak typeof(alert) weakAlert = alert;
UIAlertAction *destructive = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        NSLog(@"destructive");
        //点击确认按钮时,获取文本框的内容
        NSArray *textArray = [weakAlert textFields];
        UITextField *nameText = textArray[0];
        UITextField *pwdText = textArray[1];
        if ([nameText.text isEqualToString:@"123"] && [pwdText.text isEqualToString:@"456"]) {
            NSLog(@"登录成功");
        }else{
            NSLog(@"账号密码错误");
        }    
    }];

最后实现了一个登录的小demo:效果如下:
demo效果
代码以上传github

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值