IOS学习之UIAlertController

这篇博客介绍了iOS8后UIAlertView被UIAlertController取代的原因,包括UIAlertController的简单使用、在AppDelegate中的应用以及style的选择。重点讲解了如何初始化UIAlertController,创建UIAlertAction,以及在AppDelegate中呈现控制器的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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中最多只能添加一个。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值