警告框(AlertView)是模態的——不把它關掉,使用者就什麼都不能做。正因如此,它不該被當成「順手提示」的工具,以下幾種情況才適合使用:
1. 應用無法繼續運行。例如記憶體不足、沒有網路連線。這種狀況通常只需要一個按鈕。
2. 需要詢問替代方案。例如目前無法執行,詢問使用者是否改用 3G 網路繼續。
3. 需要取得操作授權。涉及存取隱私資料時(定位、相簿等),必須由使用者明確授權。
至於操作表(ActionSheet),它的定位不同:適合在「有多個選項可選」時使用,例如把某張圖片分享到家新浪微博或 Facebook。
// 實作 UIAlertViewDelegate
// 這個委派在範例中其實沒實際用途,純粹練手;
// 因為警告框有兩個按鈕,索引 No 為 0、Yes 為 1
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
NSLog(@"buttonIndex = %li", (long)buttonIndex);
}
// 實作 UIActionSheetDelegate
// 同樣只是把被按下的索引輸出到主控台,用以確認回應是否正確
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
NSLog(@"buttonIndex = %li", (long)buttonIndex);
}
- (IBAction)testAlertView:(id)sender {
// delegate 參數用於設定警告框的委派物件
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Alert"
message:@"Alert text goes here"
delegate:self
cancelButtonTitle:@"No"
otherButtonTitles:@"Yes", nil];
[alertView show];
}
- (IBAction)testActionSheet:(id)sender {
// cancelButtonTitle 設定取消按鈕標題
// destructiveButtonTitle 設定破壞性按鈕,只能有一個,且固定顯示在最上方
UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:nil
delegate:self
cancelButtonTitle:@"取消"
destructiveButtonTitle:@"破壞性按鈕"
otherButtonTitles:@"新浪微博", nil];
// 套用系統自動樣式
actionSheet.actionSheetStyle = UIActionSheetStyleAutomatic;
[actionSheet showInView:self.view];
}破壞性按鈕(destructive)在 iOS 7 之後會以紅字呈現,專門用來標示「刪除」「退出」這類不可回復的操作,別拿來放一般功能。
另外,showInView: 在 iPhone 上會以底部彈出的形式呈現,但在 iPad 上必須改用 showFromRect:inView:animated: 或 popover 的呈現方式,否則會出問題。
最後要留意的是,UIAlertView 與 UIActionSheet 從 iOS 8 起已被標記為廢棄,新專案請直接使用 UIAlertController,並以 preferredStyle 區分 alert 與 actionSheet 兩種樣式。