iOS8 中的UIAlertController

iOS 8.3 以后UIAlertView,跟UIActionSheet都不被推荐使用了,虽然一直知道如此,可是由于手里的老代码都是用的UIAlertView,因此历来没真正使用过这个UIAlertController。今天写一个Demo用到提示框,因此试一下。html

##UIAlertControllerios

跟UIAlertView相比,UIAlertController再也不须要实现代理方法,也无需指定按钮;建立方法:git

//建立控制器
UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"提示:" message:@"我是一条信息" preferredStyle:UIAlertControllerStyleActionSheet];
复制代码

特别注意第三个参数,它决定了样式是对话框(alert)仍是上拉菜单(actionSheet)。github

建立好控制器以后,经过UIAlertAction来给控制器添加动做按钮。bash

//建立动做按钮:
UIAlertAction *action0 = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSLog(@"OK selected");
    }];
UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        NSLog(@"Cancel selected");
    }];
//把按钮添加到控制器
[alertVC addAction:action0];
复制代码

动做按钮样式共三张:default,destructive,cancel;值得注意的是若是控制器的样式选择了actionSheet,那么它的destructive按钮永远在最前面,不管添加顺序是怎样的,cancel则永远都在最后,并且只能有一个cancel类型的按钮。spa

若是你的程序是写在iPhone上的,那么很不幸你基本跟下面的内容失之交臂了,而下面的内容才是真正有趣的部分代理

因为我写demo的时候用的设备是iPad,因此当我经过上面的代码尝试actionSheet样式的时候,我遇到了这个错误: code

屏幕快照 2016-01-20 23.11.51.png

那么这是怎么一回事呢?原来,在常规宽度的设备上,上拉菜单是以弹出视图的形式展示。弹出视图必需要有一个可以做为源视图或者栏按钮项目的描点(anchor point)。而iOS8 以后,新出了一个UIPopoverPresentationController类来替代以前的UIPopoverController。htm

##UIPopoverPresentationController 给UIAlertController配置popoverPresentationController:ip

UIPopoverPresentationController *popover = alertVC.popoverPresentationController;
    if (popover) {
        popover.sourceView = sender;
        popover.sourceRect = sender.bounds;
        popover.permittedArrowDirections = UIPopoverArrowDirectionAny;
    }
    
    [self presentViewController:alertVC animated:YES completion:nil];
复制代码

iOS 8以后,咱们再也不须要给出弹出框的大小,UIAlertController将会根据设备大小自适应弹出框的大小。而且在iPhone或者紧缩宽度的设备中它将会返回nil值。

配置好了popoverPresentationController,不管是在iPhone还iPad上,都没问题咯。

最后,UIAlertController的popoverPresentationController取消了Canle样式的action,由于用户经过点击弹出视图外的区域也能够取消弹出视图,所以不须要了。

参考文章

我是源码

相关文章
相关标签/搜索