IOS学习之UIAlertController

IOS8之后UIAlertView被废弃,UIAlertController成为主流,比起UIAlertView,UIAlertController省去了繁琐的代理方法,结构更加清晰,且耦合度更低,方便我们进行二次封装。

1. UIAlertController的简单使用

UIAlertController的初始化跟UIAlertView非常类似,只是把按键创建分离了出来:

UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"标题" 
message:@"正文内容" preferredStyle:UIAlertControllerStyleAlert];

按键的创建是通过UIAlertAction:

UIAlertAction *confirm = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault 
handler:^(UIAlertAction * _Nonnull action){  
    //确定按扭点击时调用  
}];  
UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel 
handler:nil]; 

下一步就是把action绑定alert:

[alert addAction:confirm ];  
[alert addAction:cancel];

最后show出来就可以了:

[self presentViewController:alert animated:YES completion:nil];

2. 在AppDelegate中的使用

然而问题是我们经常要在AppDelegate中使用UIAlertController,而AppDelegate是没有presentViewController方法的,怎么办呢?好办,给它一个window,它能还你一个present:

UIWindow   *alertWindow = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
alertWindow.rootViewController = [[UIViewController alloc] init];
alertWindow.windowLevel = UIWindowLevelAlert + 1;
[alertWindow makeKeyAndVisible];
[alertWindow.rootViewController presentViewController:alert animated:YES completion:nil];

3. style

UIAlertControllerStyle在枚举中看到,是两种style:

typedefNS_ENUM(NSInteger, UIAlertControllerStyle) {
    UIAlertControllerStyleActionSheet =0,  // 就是原来的UIAlertSheet
    UIAlertControllerStyleAlert            // 就是原来的UIAlertView
} NS_ENUM_AVAILABLE_IOS(8_0);

UIAlertControllerStyleActionSheet 就是下面弹出框
UIAlertControllerStyleAlert中间弹出框

UIAlertActionStyle三种:

typedefNS_ENUM(NSInteger, UIAlertActionStyle) {
    UIAlertActionStyleDefault =0,   // 默认样式
    UIAlertActionStyleCancel,       // 取消样式
    UIAlertActionStyleDestructive   // 点击按钮为红色
} NS_ENUM_AVAILABLE_IOS(8_0);

需要注意的是UIAlertActionStyleCancel,不管你add到UIAlertController的顺序前后,在只有两个按钮的时候,取消按钮在左边,按钮在两个以上的时候会排在最后,并且在同一个UIAlertController中最多只能添加一个。

发布了12 篇原创文章 · 获赞 44 · 访问量 11万+

猜你喜欢

转载自blog.csdn.net/wbshuang09/article/details/70310053
今日推荐