IOS 模态弹窗与操作版使用 UIAlertController

IOS8 以后UIAlertView 改用 UIAlertController 实现模态窗和操作板。UIAlertController 的使用与UIAlerView 非常不同,它实际上是把弹窗内容与显示方式、按钮列表、分离。实现起来非常简单。如下

1.调用静态方法创建弹窗控制器 alertControllerWithTitle

声明弹窗控制器,title 表示弹窗的标题,message表示弹窗文字内容,重点是preferredStyle 表示弹窗的显示方式,UIAlertControllerStyleActionSheet操作版方式显示,UIAlertControllerStyleAlert 模态窗方式

 // 创建控制器
    UIAlertController* alertConrtoll = [UIAlertController alertControllerWithTitle:@"错误" message:@"网络错误,获取失败" preferredStyle:UIAlertControllerStyleActionSheet];
2.为弹窗控制器增加按钮 UIAlertAction

UIAlertActions 是弹窗按钮类,通过静态方法actionWithTitle 创建,style表示按钮风格,handler是按钮被点击的回调函数。我们创建完按钮组件通过 addAction加入弹窗控制器

 // 创建弹窗按钮组件
    UIAlertAction* okBtn = [UIAlertAction actionWithTitle:@"好的" style:UIAlertActionStyleDefault handler: nil];
    UIAlertAction* cancelBtn = [UIAlertAction actionWithTitle:@"重新获取" style:UIAlertActionStyleCancel handler: nil];
    // 添加按钮
    [alertConrtoll addAction:okBtn];
    [alertConrtoll addAction:cancelBtn];
显示弹窗

显示弹窗和插入视图控制器方法一致。

[self presentViewController:alertConrtoll animated:YES completion:nil];
UIAlertController 属性
名称类型说明默认值
titleNSString标题
preferredStyleUIAlertControllerStyle弹窗显示方式,只读
actionsNSArray<UIAlertAction *>弹窗按钮列表,只读
UIAlertAction 属性
名称类型说明默认值
enabledBOOL是否启用
titleNSString标题
styleUIAlertActionStyle按钮风格UIAlertActionStyleDefault
UIAlertController API
  • + (instancetype)alertControllerWithTitle:(nullable NSString *)title message:(nullable NSString *)message preferredStyle:(UIAlertControllerStyle)preferredStyle 创建弹窗控制器并且设置标题,内容,显示风格
  • - (void)addTextFieldWithConfigurationHandler:(void (^ __nullable)(UITextField *textField))configurationHandler 添加可输入弹窗
UIAlertAction API
  • + (instancetype)actionWithTitle:(nullable NSString *)title style:(UIAlertActionStyle)style handler:(void (^ __nullable)(UIAlertAction *action))handler 创建弹窗按钮并且设置标题和风格、处理事件
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

杨周龙

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值