UIAlertController是iOS8之后出现的,代替了UIAlertView。UIAlertView大家都很熟悉了,初始化可以设置文案,通过代理做点击处理。
而UIAlertController会更简单,它的点击处理是通过blcok完成的。
示例代码:
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"your title" message:@"your message" preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
[self.navigationController popViewControllerAnimated:YES];
}];
UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:nil];
[alertController addAction:cancelAction];
[alertController addAction:okAction];
[self presentViewController:alertController animated:YES completion:nil];其中,UIAlertAction的style可以有如下选择:
typedef NS_ENUM(NSInteger, UIAlertActionStyle) {
UIAlertActionStyleDefault = 0,默认样式
UIAlertActionStyleCancel,取消样式
UIAlertActionStyleDestructive 红色央视
} NS_ENUM_AVAILABLE_IOS(8_0);cancel风格的话,不管你add到alertController上的顺序,在只有两个按钮的时候,都会按苹果的默认风格把取消按钮放在左边。(在有三个及其以上的时候会排在最后,这个你也可以自己试一下)
后面发现了,UIAlertActionStyleCancel 也就是取消样式的 UIAlertAction 在同一个UIAlertController中最多只能添加一个,多了就会崩溃。 将会报错:
'UIAlertController can only have one action with a style of UIAlertActionStyleCancel'
(UIAction为两个时)取消样式的action是会加在左边的;(UIAction为多个时)在最下面
本文介绍了UIAlertController的基本用法,它是iOS 8之后替代UIAlertView的新组件。通过示例代码展示了如何创建UIAlertController并添加不同样式的UIAlertAction,包括取消样式按钮的特殊限制。
1136

被折叠的 条评论
为什么被折叠?



