iOS 8 之後,蘋果放棄了 UIAlertView 與 UIActionSheet,改以 UIAlertController 把兩者整合為一。新 API 的精簡程度令人愉悅:過去要寫一大片的程式碼,現在幾行就能搞定。
UIAlertController* alert = [UIAlertController alertControllerWithTitle:@"My Alert"
message:@"This is an alert."
preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK"
style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action) {
NSLog(@"你好你好");
}];
UIAlertAction* defaultAction2 = [UIAlertAction actionWithTitle:@"OK2"
style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action) {
NSLog(@"你好你好");
}];
[alert addAction:defaultAction];
[alert addAction:defaultAction2];
[self presentViewController:alert animated:YES completion:nil];
初始化的寫法與舊版差異不大,真正的改變是事件綁定方式。蘋果新增了 UIAlertAction,一個 Action 對應一個按鈕與一段回呼,加到 alert 上即可。這比舊版靠 delegate 分支判斷 buttonIndex 的寫法直觀得多,也不再有 index 錯位的心智負擔。
style 有兩種可選:UIAlertActionStyleDefault 是普通樣式,UIAlertActionStyleCancel 會加粗並置於最下方,UIAlertActionStyleDestructive 則以紅字提示危險操作。
只需把 preferredStyle 換成 UIAlertControllerStyleActionSheet,其餘程式碼完全不變,這正是整合帶來的紅利。
[alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
textField.placeholder = @"輸入用戶名";
}];
在 configuration handler 裡可以預先設定 placeholder、初始文字,甚至鍵盤型別。使用者輸入的內容可從 alert.textFields.firstObject.text 取得。
實務上有兩個常踩的坑:一是 present 之前務必確認自己不在畫面消失或正在切換的狀態,否則會拿到「whose view is not in the window hierarchy」的警告;二是同一時刻只應存在一個 alert,連續彈出多個會讓其中幾個永遠顯示不出來。