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

iOS 8 對話框新做法:全面解析 UIAlertController

編輯:iOS 開發基礎

iOS 8 帶來的最重要變化之一,是讓介面變得更具適應性與彈性。也正因為如此,不少視圖控制器的實作思路被徹底改寫。全新的 UIPresentationController 負責處理視圖控制器之間的轉場動畫,以及旋轉、尺寸變化這類自適應場景,替開發者省下了大量手工計算的麻煩。與此同時,Alert View、Action Sheet、Popover 以及 Search Bar Controller 這些老面孔也都有明顯改動。本文聚焦其中的對話框與上拉選單,並同時給出 Objective-C 與 Swift 兩種寫法。

舊日的 UIAlertView

從 iOS 5 開始,UIAlertView 就一直是 iOS 上最典型的提示方塊,樣式多年未變。下面的程式碼示範了如何建立一個帶有「取消」與「好的」兩個按鈕的對話框。

Objective-C 版本:

UIAlertView *alertview = [[UIAlertView alloc] initWithTitle:@"標題" message:@"這個是UIAlertView的默認樣式" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"好的", nil]; [alertview show];

UIAlertView 的預設樣式

Swift 版本的初始化限制更多:只能建立帶一個取消按鈕的對話框。你或許會看到那個帶 otherButtonTitles 的 init 方法,可惜它根本過不了編譯。

var alertView = UIAlertView(title: "標題", message: "這個是UIAlertView的默認樣式", delegate: self, cancelButtonTitle: "取消") alertView.show()

Swift 版本的 UIAlertView

若想在 Swift 裡做出跟 Objective-C 相同效果的對話框,只能繞個彎,麻煩歸麻煩,為了目的總還是能做到的:

var alertView = UIAlertView() alertView.delegate = self alertView.title = "標題" alertView.message = "這個是UIAlertView的默認樣式" alertView.addButtonWithTitle("取消") alertView.addButtonWithTitle("好的") alertView.show()

另外,透過修改 UIAlertView 的 alertViewStyle 屬性,還能做出文字輸入、密碼輸入甚至登入表單的樣子。

UIAlertView 文字對話框

UIAlertView 密碼對話框

UIAlertView 登入對話框

UIAlertViewDelegate 協定提供了回應按鈕點擊的回呼方法;而實作 alertViewShouldEnableOtherButton: 之後,還能依文字框內容動態決定其他按鈕是否可點。

需要提醒的是,蘋果在 iOS 8 已不再建議使用 UIAlertView,取而代之的是 UIAlertController。

UIAlertController 登場

在功能上,UIAlertController 完全涵蓋了原本的 UIAlertView 與 UIActionSheet,以模組化的方式統一替換兩者。究竟呈現為對話框還是上拉選單,取決於建立控制器時設定的 preferredStyle。

一個最簡單的對話框

把兩段程式碼放在一起比較,你會發現建立 UIAlertController 的寫法與 UIAlertView 幾乎如出一轍:

Objective-C 版本:

UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"標題" message:@"這個是UIAlertController的默認樣式" preferredStyle:UIAlertControllerStyleAlert];

Swift 版本:

var alertController = UIAlertController(title: "標題", message: "這個是UIAlertController的默認樣式", preferredStyle: UIAlertControllerStyle.Alert)

不再需要指定 delegate,也不必在初始化時就把按鈕塞進去。但要特別留意第三個參數,務必確認自己選的是 alert 還是 actionSheet。

按鈕則由 UIAlertAction 負責。每個 UIAlertAction 由標題、樣式,以及使用者點選後要執行的程式碼區塊組成。UIAlertActionStyle 提供三種選項:Default(一般)、Cancel(取消)與 Destructive(警示)。想還原前面那組按鈕效果,只要建立兩個 action 並加入控制器即可。

Objective-C 版本:

UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]; UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"好的" style:UIAlertActionStyleDefault handler:nil]; [alertController addAction:cancelAction]; [alertController addAction:okAction];

Swift 版本:

var cancelAction = UIAlertAction(title: "取消", style: UIAlertActionStyle.Cancel, handler: nil) var okAction = UIAlertAction(title: "好的", style: UIAlertActionStyle.Default, handler: nil) alertController.addAction(cancelAction) alertController.addAction(okAction)

最後,像呈現一般視圖控制器那樣把它顯示出來:

Objective-C 版本:

[self presentViewController:alertController animated:YES completion:nil];

Swift 版本:

self.presentViewController(alertController, animated: true, completion: nil)

UIAlertController 預設樣式

按鈕的排列順序取決於 addAction 的呼叫順序。依《iOS 使用者介面指南》的建議,雙按鈕對話框應把取消放在左側。另外,取消樣式的 action 只能有一個,若加入第二個就會拋出執行期例外:

* Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'UIAlertController can only have one action with a style of UIAlertActionStyleCancel'

「警示」樣式

先來看個例子。這次把「好的」換成「重置」按鈕。

Objective-C 版本:

UIAlertAction *resetAction = [UIAlertAction actionWithTitle:@"重置" style:UIAlertActionStyleDestructive handler:nil]; [alertController addAction:resetAction];

Swift 版本:

var resetAction = UIAlertAction(title: "重置", style: UIAlertActionStyle.Destructive, handler: nil) alertController.addAction(resetAction)

「警示」樣式

可以看到「重置」是紅色的。依蘋果的定義,Destructive 樣式專用於可能改動或刪除資料的操作,紅色正是為了提醒使用者三思而後行。

自訂文字輸入對話框

UIAlertController 的彈性意味著你不必被內建樣式綁住。過去只能從預設、文字框、密碼框、帳號密碼框這幾種固定樣式中挑,現在則可以加入任意數量的 UITextField,並使用它全部的屬性。加入文字框時,需要提供一個用來設定它的程式碼區塊。

舉例來說,要重建帳號密碼對話框,只要加入兩個文字框、分別設定 placeholder,再把密碼欄設為安全輸入即可。

Objective-C 版本:

UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"文字對話框" message:@"登入和密碼對話框示例" preferredStyle:UIAlertControllerStyleAlert]; [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField){ textField.placeholder = @"登入"; }]; [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) { textField.placeholder = @"密碼"; textField.secureTextEntry = YES; }];

Swift 版本:

alertController.addTextFieldWithConfigurationHandler { (textField: UITextField!) -> Void in textField.placeholder = "登入" } alertController.addTextFieldWithConfigurationHandler { (textField: UITextField!) -> Void in textField.placeholder = "密碼" textField.secureTextEntry = true }

按下「好的」時,把文字框裡的值讀出來:

Objective-C 版本:

UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"好的" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) { UITextField *login = alertController.textFields.firstObject; UITextField *password = alertController.textFields.lastObject; ... }];

Swift 版本:

var okAction = UIAlertAction(title: "好的", style: UIAlertActionStyle.Default) { (action: UIAlertAction!) -> Void in var login = alertController.textFields?.first as UITextField var password = alertController.textFields?.last as UITextField }

若想重現舊有的 alertViewShouldEnableOtherButton: 行為,會稍微棘手一些。假設需求是「登入欄至少輸入 3 個字元才啟用好的按鈕」,由於 UIAlertController 沒有對應的 delegate 方法,我們得自己替文字框掛一個 Observer。觀察者模式定義了物件間一對多的依賴關係,當某個物件狀態改變時,所有依賴它的物件都會收到通知並更新。在設定區塊中加入以下程式碼即可:

Objective-C 版本:

[alertController addTextFieldWithConfigurationHandler:^(UITextField *textField){ ... [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(alertTextFieldDidChange:) name:UITextFieldTextDidChangeNotification object:textField]; }];

Swift 版本:

alertController.addTextFieldWithConfigurationHandler { (textField: UITextField!) -> Void in ... NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("alertTextFieldDidChange:"), name: UITextFieldTextDidChangeNotification, object: textField) }

視圖控制器釋放時必須移除這個 Observer,做法是在每個按鈕的 handler 區塊(以及其他任何可能釋放控制器的地方)補上移除程式碼。以 okAction 為例:

Objective-C 版本:

UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"好的" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) { ... [[NSNotificationCenter defaultCenter] removeObserver:self name:UITextFieldTextDidChangeNotification object:nil]; }];

Swift 版本:

var okAction = UIAlertAction(title: "好的", style: UIAlertActionStyle.Default) { (action: UIAlertAction!) -> Void in ... NSNotificationCenter.defaultCenter().removeObserver(self, name: UITextFieldTextDidChangeNotification, object: nil) }

對話框顯示之前,先把「好的」按鈕凍結:

Objective-C 版本:

okAction.enabled = NO;

Swift 版本:

okAction.enabled = false

接著在通知回呼裡,先檢查「登入」欄的內容,再決定是否啟用按鈕。

Objective-C 版本:

- (void)alertTextFieldDidChange:(NSNotification *)notification{ UIAlertController *alertController = (UIAlertController *)self.presentedViewController; if (alertController) { UITextField *login = alertController.textFields.firstObject; UIAlertAction *okAction = alertController.actions.lastObject; okAction.enabled = login.text.length > 2; } }

Swift 版本:

func alertTextFieldDidChange(notification: NSNotification){ var alertController = self.presentedViewController as UIAlertController? if (alertController != nil) { var login = alertController!.textFields?.first as UITextField var okAction = alertController!.actions.last as UIAlertAction okAction.enabled = countElements(login.text) > 2 } }

UIAlertController 的登入與密碼對話框示例

如此一來,除非「登入」欄填滿 3 個字元以上,「好的」按鈕會一直保持不可點擊。

上拉選單 Action Sheet

當需要讓使用者從一串選項中挑一個時,上拉選單就非常合適。與對話框不同,上拉選單的呈現方式與裝置尺寸有關:在 iPhone(緊湊寬度)上它從螢幕底部升起;在 iPad(常規寬度)上則以彈出框形式出現。

建立方式與對話框幾乎相同,差別只在樣式。

Objective-C 版本:

UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"保存或刪除數據" message:@"刪除數據將不可恢復" preferredStyle: UIAlertControllerStyleActionSheet];

Swift 版本:

var alertController = UIAlertController(title: "保存或刪除數據", message: "刪除數據將不可恢復", preferredStyle: UIAlertControllerStyle.ActionSheet)

加入按鈕的方式也一樣。

Objective-C 版本:

UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]; UIAlertAction *deleteAction = [UIAlertAction actionWithTitle:@"刪除" style:UIAlertActionStyleDestructive handler:nil]; UIAlertAction *archiveAction = [UIAlertAction actionWithTitle:@"保存" style:UIAlertActionStyleDefault handler:nil]; [alertController addAction:cancelAction]; [alertController addAction:deleteAction]; [alertController addAction:archiveAction];

Swift 版本:

var cancelAction = UIAlertAction(title: "取消", style: UIAlertActionStyle.Cancel, handler: nil) var deleteAction = UIAlertAction(title: "刪除", style: UIAlertActionStyle.Destructive, handler: nil) var archiveAction = UIAlertAction(title: "保存", style: UIAlertActionStyle.Default, handler: nil) alertController.addAction(cancelAction) alertController.addAction(deleteAction) alertController.addAction(archiveAction)

但上拉選單不能加入文字框,硬加的話會得到這個執行期例外:

* Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Text fields can only be added to an alert controller of style UIAlertControllerStyleAlert'

接著在 iPhone 或其他緊湊寬度裝置上呈現,一切正常。

Objective-C 版本:

[self presentViewController:alertController animated:YES completion:nil];

Swift 版本:

self.presentViewController(alertController, animated: true, completion: nil)

iPhone 上的上拉選單效果

取消按鈕永遠固定在選單最底部,與加入順序無關;其餘按鈕則依加入順序由上而下排列。《iOS 使用者介面指南》要求「毀壞」樣式的按鈕必須排在最前面。

不過別高興得太早,還藏著一個比較隱蔽的問題。在 iPad 等常規寬度裝置上執行會拋出例外:

Terminating app due to uncaught exception 'NSGenericException', reason: 'UIPopoverPresentationController (<_uialertcontrolleractionsheetregularpresentationcontroller: 0x7fc619588110>) should have a non-nil sourceView or barButtonItem set before the presentation occurs.'

如前所述,常規寬度下上拉選單以彈出框呈現,而彈出框必須有一個作為定位錨點的 sourceView 或 barButtonItem。本例是以普通的 UIButton 觸發選單,那就把它當作錨點。

好消息是 iOS 8 之後我們不必再費心計算彈出框尺寸,UIAlertController 會依裝置大小自適應;在 iPhone 等緊湊寬度裝置上,popoverPresentationController 會回傳 nil。設定程式碼如下:

Objective-C 版本:

UIPopoverPresentationController *popover = alertController.popoverPresentationController; if (popover){ popover.sourceView = sender; popover.sourceRect = sender.bounds; popover.permittedArrowDirections = UIPopoverArrowDirectionAny; }

Swift 版本:

var popover = alertController.popoverPresentationController if (popover != nil){ popover?.sourceView = sender popover?.sourceRect = sender.bounds popover?.permittedArrowDirections = UIPopoverArrowDirection.Any }

iPad 上的上拉選單效果

UIPopoverPresentationController 同樣是 iOS 8 新增的類別,用來取代 UIPopoverController。此時上拉選單以固定在來源按鈕上的彈出框顯示。

值得留意的是,使用彈出框時 UIAlertController 會自動把取消按鈕拿掉——使用者點擊彈出框外圍即可取消,取消按鈕也就顯得多餘了。

釋放對話框控制器

一般情況下,使用者選完動作後控制器會自行釋放,但你也可以在需要時用程式碼主動關閉,方式與關閉其他視圖控制器相同。建議在 App 進入背景時就把對話框或上拉選單收起來。假設我們正在監聽 UIApplicationDidEnterBackgroundNotification,就可以在回呼裡關掉所有正在顯示的控制器(記得先在 viewDidLoad 中註冊觀察者)。

Objective-C 版本:

- (void)didEnterBackground:(NSNotification *)notification { [[NSNotificationCenter defaultCenter] removeObserver:self name:UITextFieldTextDidChangeNotification object:nil]; [self.presentedViewController dismissViewControllerAnimated:NO completion:nil]; }

Swift 版本:

func didEnterackground(notification: NSNotification){ NSNotificationCenter.defaultCenter().removeObserver(self, name: UITextFieldTextDidChangeNotification, object: nil) self.presentedViewController?.dismissViewControllerAnimated(false, completion: nil) }

別忘了,所有文字框的 Observer 也都要一併移除,才能確保運行安全。

小結

文章寫到這裡已經不短,希望對你有幫助。原有的 UIAlertView 與 UIActionSheet 在 iOS 8 中依然能正常運作,所以不必急著全面改寫程式碼(何況本文用到的許多 API 僅在 iOS 8 以上可用)。完整範例程式碼已放在筆者的 GitHub 上,分為 AlertController - ObjC 與 AlertController - Swift 兩份。

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