要說明一點,蘋果官方如今並不提倡在iOS 8及以上版本中使用UIAlertView,取而代之的是UIAlertController。下面咱們就來介紹UIAlertController的使用方法。html
UIAlertControllerios
在iOS 8中,UIAlertController在功能上是和UIAlertView以及UIActionSheet相同的,UIAlertController以一種模塊化替換的方式來代替這兩貨的功能和做用。是使用對話框(alert)仍是使用上拉菜單(action sheet),就取決於在建立控制器時,您是如何設置首選樣式的。swift
一個簡單的對話框例子app
您能夠比較一下兩種不一樣的建立對話框的代碼,建立基礎UIAlertController的代碼和建立UIAlertView的代碼很是類似:模塊化
Objective-C版本:spa
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"標題" message:@"這個是UIAlertController的默認樣式" preferredStyle:UIAlertControllerStyleAlert];
swift版本:代理
var alertController = UIAlertController(title: "標題", message: "這個是UIAlertController的默認樣式", preferredStyle: UIAlertControllerStyle.Alert)
同建立UIAlertView相比,咱們無需指定代理,也無需在初始化過程當中指定按鈕。不過要特別注意第三個參數,要肯定您選擇的是對話框樣式仍是上拉菜單樣式。code
經過建立UIAlertAction的實例,您能夠將動做按鈕添加到控制器上。UIAlertAction由標題字符串、樣式以及當用戶選中該動做時運行的代碼塊組成。經過UIAlertActionStyle,您能夠選擇以下三種動做樣式:常規(default)、取消(cancel)以及警示(destruective)。爲了實現原來咱們在建立UIAlertView時建立的按鈕效果,咱們只需建立這兩個動做按鈕並將它們添加到控制器上便可。htm
Objective-C版本:字符串
UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]; UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"好的" style:UIAlertActionStyleDefault handler:nil]; [alertController addAction:cancelAction]; [alertController addAction:okAction];
swift版本:
var cancelAction = UIAlertAction(title: "取消", style: UIAlertActionStyle.Cancel, handler: nil) var okAction = UIAlertAction(title: "好的", style: UIAlertActionStyle.Default, handler: nil) alertController.addAction(cancelAction) alertController.addAction(okAction)
最後,咱們只需顯示這個對話框視圖控制器便可:
Objective-C版本:
[self presentViewController:alertController animated:YES completion:nil];
swift版本:
self.presentViewController(alertController, animated: true, completion: nil)
UIAlertController默認樣式
按鈕顯示的次序取決於它們添加到對話框控制器上的次序。通常來講,根據蘋果官方制定的《iOS 用戶界面指南》,在擁有兩個按鈕的對話框中,您應當將取消按鈕放在左邊。要注意,取消按鈕是惟一的,若是您添加了第二個取消按鈕,那麼你就會獲得以下的一個運行時異常:
Terminating app due to uncaught exception ‘NSInternalInconsistencyException’, reason: ‘UIAlertController can only have one action with a style of UIAlertActionStyleCancel’
異常信息簡潔明瞭,咱們在此就不贅述了。
demo代碼:
-(void)deleted { UIAlertController * alert = [UIAlertController alertControllerWithTitle:@"提醒" message:@"肯定要刪除當前水票嗎?" preferredStyle:UIAlertControllerStyleAlert]; UIAlertAction * cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]; //handler爲手勢方法添加處,這裏就代替了以前UIAlertView中的代理協議方法,十分方便 UIAlertAction * okAction = [UIAlertAction actionWithTitle:@"肯定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) { [self okDeleted]; }]; [alert addAction:cancelAction]; [alert addAction:okAction]; [self presentViewController:alert animated:YES completion:nil]; } -(void)okDeleted { DLog(@"點到刪除啦 啊啦啦啦啦"); }
參考來源: