您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 使用技巧 >> iOS 7 技巧

iOS UIAlertController 基礎用法與 delegate、block 之別

編輯:iOS 7 技巧

從 iOS 8 開始,UIAlertView 與 UIActionSheet 已被蘋果標記為不建議使用,取而代之的是 UIAlertController。它繼承自 UIViewController,因此呈現方式不是 show,而是一般的 present。本文整理最基本的用法與觀念轉換。

一、為什麼要換

舊的 UIAlertView / UIActionSheet 並非真正的 view controller,需要 delegate 才能实现回呼,寫法繁瑣且容易忘記實作。UIAlertController 改為繼承 UIViewController,並以 block 取代 delegate,API 直觀許多。

二、四步驟完成一個提示框

1. 建立 UIAlertController

UIAlertController *alertController =
    [UIAlertController alertControllerWithTitle:@"Success"
                                        message:nil
                                 preferredStyle:UIAlertControllerStyleAlert];

2. 建立 UIAlertAction

UIAlertAction *doneAction =
    [UIAlertAction actionWithTitle:@"Done"
                             style:UIAlertActionStyleDefault
                           handler:^(UIAlertAction *action) {
                               NSLog(@"123");
                           }];

3. 把 action 加入 controller

[alertController addAction:doneAction];

4. 以 present 方式顯示

[[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];

四、delegate 與 block 的差別

兩者並沒有本質上的優劣,只是回呼方式不同,解決的都是「未來某個時間請呼叫我」這個問題。

  • delegate:複用性較好。建立一個 delegate 實例後可服務多個元件,重複性低,適合一對多的通知情境。
  • block:更直觀。相關程式碼集中在同一處,閱讀時不必在各檔案間跳轉,理解成本更低。

近年蘋果官方 API 大量採用 block,某種程度上也反映了這個趨勢。

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