從 iOS 8 開始,UIAlertView 與 UIActionSheet 已被蘋果標記為不建議使用,取而代之的是 UIAlertController。它繼承自 UIViewController,因此呈現方式不是 show,而是一般的 present。本文整理最基本的用法與觀念轉換。
舊的 UIAlertView / UIActionSheet 並非真正的 view controller,需要 delegate 才能实现回呼,寫法繁瑣且容易忘記實作。UIAlertController 改為繼承 UIViewController,並以 block 取代 delegate,API 直觀許多。
UIAlertController *alertController =
[UIAlertController alertControllerWithTitle:@"Success"
message:nil
preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *doneAction =
[UIAlertAction actionWithTitle:@"Done"
style:UIAlertActionStyleDefault
handler:^(UIAlertAction *action) {
NSLog(@"123");
}];
[alertController addAction:doneAction];
[[UIApplication sharedApplication].keyWindow.rootViewController
presentViewController:alertController animated:YES completion:nil];
如果想要類似 UIActionSheet 的底部選單樣式,只要把第一步的 UIAlertControllerStyleAlert 換成 UIAlertControllerStyleActionSheet 即可。
若在 iOS 7 上執行到這個 API 會直接 crash,因此需要做版本判斷。完整範例:
UIAlertController *alert =
[UIAlertController alertControllerWithTitle:@"title"
message:@"message"
preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *cancel =
[UIAlertAction actionWithTitle:@"取消"
style:UIAlertActionStyleCancel
handler:nil];
UIAlertAction *confirm =
[UIAlertAction actionWithTitle:@"確定"
style:UIAlertActionStyleDefault
handler:^(UIAlertAction *action) {
[mainViewDelegate doBackupWithTag:BACKUP_STATISTICS_TAG_CONFIRM];
}];
[alert addAction:cancel];
[alert addAction:confirm];
[self presentViewController:alert animated:YES completion:nil];
兩者並沒有本質上的優劣,只是回呼方式不同,解決的都是「未來某個時間請呼叫我」這個問題。
近年蘋果官方 API 大量採用 block,某種程度上也反映了這個趨勢。