從 iOS 8 升級到 iOS 9 的過程中,彈出提示框的方式發生了不小的變化。在 Xcode 7、iOS 9.0 SDK 中,官方已經明確表示不再推薦使用 UIAlertView,而是要求改用 UIAlertController。下面我們透過程式碼實際示範這個轉變。
先示範透過點擊按鈕彈出提示框的舊寫法:
#import ViewController.h @interface ViewController () @property(strong,nonatomic) UIButton *button; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; self.button = [[UIButton alloc] initWithFrame:CGRectMake(0, 100, [[UIScreen mainScreen] bounds].size.width, 20)]; [self.button setTitle:@跳轉 forState:UIControlStateNormal]; [self.button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal]; [self.view addSubview:self.button]; [self.button addTarget:self action:@selector(clickMe:) forControlEvents:UIControlEventTouchUpInside]; } -(void)clickMe:(id)sender{ UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@提示 message:@按鈕被點擊了 delegate:self cancelButtonTitle:@確定 otherButtonTitles:nil, nil]; [alert show]; } @end
編寫上述程式碼時,會出現以下警告:

「'UIAlertView' is deprecated: first deprecated in iOS 9.0 - UIAlertView is deprecated. Use UIAlertController with a preferredStyle of UIAlertControllerStyleAlert instead」。
這段訊息說明 UIAlertView 自 iOS 9 起已被棄用,應改用 UIAlertController。不過實際運行時,這段程式碼仍然可以成功執行,不會造成 crash。

但在真正的工程開發中,我們有一條「潛規則」:把每一個警告(warning)都當成錯誤(error)來看待。因此為了順應蘋果的建議,我們就來消除這個警告,改用 UIAlertController。
#import ViewController.h @interface ViewController () @property(strong,nonatomic) UIButton *button; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; self.button = [[UIButton alloc] initWithFrame:CGRectMake(0, 100, [[UIScreen mainScreen] bounds].size.width, 20)]; [self.button setTitle:@跳轉 forState:UIControlStateNormal]; [self.button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal]; [self.view addSubview:self.button]; [self.button addTarget:self action:@selector(clickMe:) forControlEvents:UIControlEventTouchUpInside]; } -(void)clickMe:(id)sender{ //初始化提示框; UIAlertController *alert = [UIAlertController alertControllerWithTitle:@提示 message:@按鈕被點擊了 preferredStyle: UIAlertControllerStyleAlert]; [alert addAction:[UIAlertAction actionWithTitle:@確定 style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) { //點擊按鈕的響應事件; }]]; //彈出提示框; [self presentViewController:alert animated:true completion:nil]; } @end
改用 UIAlertController 後,程式碼就不再出現警告了,而運行後的視覺效果與舊寫法相同。
值得注意的是,preferredStyle 參數還有另一個選項:UIAlertControllerStyleActionSheet。選擇這個列舉型別後,效果如下:

可以發現,這個提示框會從畫面底部彈出。
透過查看程式碼你會發現,新寫法中提示框內的按鈕回應不再需要透過 delegate 委託來實現,而是直接用 addAction 在一個 block 中處理點擊事件,既直觀又方便。這正是 UIAlertController 相較於舊 API 的一大改進。