我是靠谱客的博主 过时唇彩,最近开发中收集的这篇文章主要介绍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

转载于:https://www.cnblogs.com/xiaocai-ios/p/7779806.html

最后

以上就是过时唇彩为你收集整理的AlertController提示框的全部内容,希望文章能够帮你解决AlertController提示框所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(97)

评论列表共有 0 条评论

立即
投稿
返回
顶部