把 UIActionSheet 的程式碼寫在 viewDidLoad 裡,執行後什麼都沒發生——這大概是每個人都撞過的牆。當初我還懷疑是不是 Xcode 出了問題,後來才發現自己平常都是寫在按鈕的點擊方法裡,所以才一直正常。
查了 Apple 的文件,有這麼一句:
Action sheets display a set of buttons representing several alternative choices to complete a task initiated by the user.
關鍵字是 initiated by the user。操作表單的設計前提是「使用者主動觸發了某個動作,需要從幾個選項中挑一個」,因此它必須在使用者互動的時機呈現。放在 viewDidLoad 中,畫面根本還沒完成呈現,自然不會顯示。
官方文件:https://developer.apple.com/library/ios/documentation/UserExperience/Conceptual/UIKitUICatalog/UIActionSheet.html
@interface SheetViewController : UIViewController <UIActionSheetDelegate>
@end
UIActionSheet *actionSheet = [[UIActionSheet alloc]
initWithTitle:@"first ActionSheet"
delegate:self
cancelButtonTitle:@"取消"
destructiveButtonTitle:@"刪除"
otherButtonTitles:@"保持", nil];
actionSheet.actionSheetStyle = UIActionSheetStyleBlackTranslucent;
[actionSheet showInView:self.view];
參數說明:cancelButtonTitle 與 destructiveButtonTitle 是系統提供的兩個特殊按鈕;otherButtonTitles 是你要自訂的選項,可以有多個;最後一個參數必須是 nil 作為結束標記,這點漏掉會編譯錯誤或行為異常。
#pragma mark --- UIActionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet
clickedButtonAtIndex:(NSInteger)buttonIndex
{
if (buttonIndex == 0) {
[self showAlert:@"確定"];
} else if (buttonIndex == 1) {
[self showAlert:@"第一項"];
} else if (buttonIndex == 2) {
[self showAlert:@"第二項"];
} else if (buttonIndex == 3) {
[self showAlert:@"取消"];
}
NSString *buttonTitle = [actionSheet buttonTitleAtIndex:buttonIndex];
NSLog(@"buttonTitle = %@", buttonTitle);
}
buttonIndex 對應按鈕的排列順序,從 0 開始。實務上強烈建議不要寫死數字,而是用 buttonTitleAtIndex: 取回標題再比對,或用 cancelButtonIndex、destructiveButtonIndex 這兩個屬性來判斷特殊按鈕——因為日後調整選項順序時,寫死 index 的程式碼一定會出錯。
ActionSheet 支援一種所謂的破壞性按鈕,會以紅色高亮顯示,用來警示使用者這是一個不可逆的操作,例如永久刪除一則訊息或一張照片。只要指定它的索引即可:
actionSheet.destructiveButtonIndex = 1;
與導覽列類似,操作表單也提供三種風格:
UIActionSheetStyleDefault // 預設:灰色背景配白色文字 UIActionSheetStyleBlackTranslucent // 半透明黑背景,白色文字 UIActionSheetStyleBlackOpaque // 純黑背景,白色文字
設定方式:
actionSheet.actionSheetStyle = UIActionSheetStyleBlackOpaque;
showInView: 是在目前的 view 上顯示。如果你的 App 有 tab bar 或 toolbar,改用 showFromTabBar: 或 showFromToolbar: 會更合適,因為操作表單會自動被推到底bar之上,不會互相遮擋。若從 UINavigationBar 上的按鈕觸發,則用 showFromBarButtonItem:animated:。
最後要提醒的是,UIActionSheet 在 iOS 8 之後已被 UIAlertController 取代並標記為 deprecated。新專案請直接使用 preferredStyle 設為 .actionSheet 的 UIAlertController,它同時解決了 iPhone / iPad 呈現差異的問題,也不必再實作 delegate。