您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

UIAlertController 用法詳解與範例程式碼

編輯:iOS 開發綜合

從 UIAlertView 到 UIAlertController

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 則以紅字提示危險操作。

改成 ActionSheet

只需把 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,連續彈出多個會讓其中幾個永遠顯示不出來。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved