升級到 iOS 9 SDK 之後,編譯時會看到這則警告:
'UIAlertView' is deprecated: first deprecated in iOS 9.0 — UIAlertView is deprecated. Use UIAlertController instead.
訊息本身已經把答案寫出來了:改用 UIAlertController。
UIAlertView 與 UIActionSheet 是 iOS 早期就存在的元件,它們由系統自行建立一個獨立的 UIWindow 來呈現,App 無法完全掌握其外觀與行為。隨著 iOS 版本演進,Apple 逐步把這類「系統代管的彈出層」收斂到 view controller 體系內,讓外觀能透過 iOS 8 引入的 UIAppearance 與 view controller 自訂呈現機制統一管理。UIAlertController 就是這個方向的產物。
舊寫法:
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"
message:@"確定要刪除嗎?"
delegate:self
cancelButtonTitle:@"取消"
otherButtonTitles:@"確定", nil];
[alert show];
新寫法:
UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示"
message:@"確定要刪除嗎?"
preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消"
style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
// 使用者按取消
}];
UIAlertAction *confirm = [UIAlertAction actionWithTitle:@"確定"
style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
// 使用者按確定
}];
[alert addAction:cancel];
[alert addAction:confirm];
[self presentViewController:alert animated:YES completion:nil];
不再需要 delegate。UIAlertView 用 delegate 回傳 buttonIndex,UIAlertController 則每個 action 各自帶一個 handler block,邏輯更集中,也不用再實作 alertView:clickedButtonAtIndex:。
呈現方式改成 present。必須用 presentViewController:animated:completion:,並確認當前的 view controller 正在畫面上,否則警告不會出現。
可以放文字輸入框。UIAlertView 要靠私有 API 才能加輸入框,UIAlertController 直接提供 addTextFieldWithConfigurationHandler:,這也是遷移後最常被用來改善舊程式的地方。
ActionSheet 也一起換掉。用 UIAlertControllerStyleActionSheet 取代 UIActionSheet,並注意 iPad 上要用 popoverPresentationController 指定錨點來源,否則會崩潰。
handler 裡的 self 循環參考。block 會強參考 self,若 self 又強參考 alert, theoretically 會形成循環。實務上 alert 通常是區域變數,問題不大,但在有巢狀或長期持有的場景仍應留意。
如果你的專案仍大量使用 UIAlertView,建議安排一次統一遷移,而不是新舊混用——混用的時候,同一畫面上兩個彈出層的 z-order 與外觀一致性會很難對齊。