iOS 8.3 之后UIAlertView,跟UIActionSheet都不被推薦使用了靡砌,雖然一直知道如此扩然,但是因?yàn)槭掷锏睦洗a都是用的UIAlertView觅闽,所以從來沒真正使用過這個UIAlertController帝雇。今天寫一個Demo用到提示框,所以試一下蛉拙。
UIAlertController
跟UIAlertView相比尸闸,UIAlertController不再需要實(shí)現(xiàn)代理方法,也無需指定按鈕孕锄;創(chuàng)建方法:
//創(chuàng)建控制器
UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"提示:" message:@"我是一條信息" preferredStyle:UIAlertControllerStyleActionSheet];
特別注意第三個參數(shù)室叉,它決定了樣式是對話框(alert)還是上拉菜單(actionSheet)。
創(chuàng)建好控制器之后硫惕,通過UIAlertAction來給控制器添加動作按鈕。
//創(chuàng)建動作按鈕:
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按鈕永遠(yuǎn)在最前面豁辉,無論添加順序是怎樣的,cancel則永遠(yuǎn)都在最后舀患,而且只能有一個cancel類型的按鈕徽级。
如果你的程序是寫在iPhone上的,那么很不幸你基本跟下面的內(nèi)容失之交臂了聊浅,而下面的內(nèi)容才是真正有趣的部分
由于我寫demo的時候用的設(shè)備是iPad餐抢,所以當(dāng)我通過上面的代碼嘗試actionSheet樣式的時候,我遇到了這個錯誤:
那么這是怎么一回事呢低匙?原來旷痕,在常規(guī)寬度的設(shè)備上,上拉菜單是以彈出視圖的形式展現(xiàn)顽冶。彈出視圖必須要有一個能夠作為源視圖或者欄按鈕項(xiàng)目的描點(diǎn)(anchor point)欺抗。而iOS8 之后,新出了一個UIPopoverPresentationController類來替代之前的UIPopoverController强重。
UIPopoverPresentationController
給UIAlertController配置popoverPresentationController:
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將會根據(jù)設(shè)備大小自適應(yīng)彈出框的大小间景。并且在iPhone或者緊縮寬度的設(shè)備中它將會返回nil值佃声。
配置好了popoverPresentationController,無論是在iPhone還iPad上拱燃,都沒問題咯秉溉。
最后,UIAlertController的popoverPresentationController取消了Canle樣式的action,因?yàn)橛脩敉ㄟ^點(diǎn)擊彈出視圖外的區(qū)域也可以取消彈出視圖召嘶,因此不需要了父晶。