研究 UIActionSheet 時,我直接把程式碼貼進 viewDidLoad 執行,結果怎麼跑都有問題,甚至懷疑是 Xcode 壞了。後來才想到,平常使用時都是放在某個按鈕的點擊方法裡,於是產生一個想法:UIActionSheet 必須搭配使用者動作才會生效。
查了官方文件,確實有這麼一句話印證了這個觀點:Action sheets display a set of buttons representing several alternative choices to complete a task initiated by the user. 也就是說,它本質上是用來回應使用者所發起的操作,而不是拿來在主動畫流程中自動彈出。
官方文件:
https://developer.apple.com/library/ios/documentation/UserExperience/Conceptual/UIKitUICatalog/UIActionSheet.html
@interface sheetviewViewController : UIViewController <UIActionSheetDelegate>
@end
UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"first ActionSheet"
delegate:self
cancelButtonTitle:@"取消"
destructiveButtonTitle:@"刪除"
otherButtonTitles:@"保持", nil];
actionSheet.actionSheetStyle = UIActionSheetStyleBlackTranslucent;
[actionSheet showInView:self.view];
#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);
}
初始化方法中有兩個參數是系統預留的固定項目:cancelButtonTitle 是取消按鈕,destructiveButtonTitle 是破壞性操作按鈕。otherButtonTitles 則是自行定義的項目,可以帶多個,但參數列表最後必須以 nil 結束,否則會讀到記憶體中的垃圾值。
[actionSheet showInView:self.view] 表示在目前 view 上顯示 action sheet,當然也有 showFromTabBar:、showFromToolbar: 等其他呈現方式可選。
回呼中的 buttonIndex 就是按鈕的索引,依加入順序遞增。
那顆紅色的按鈕,就是所谓的破壞性按鈕,用來對某個不可逆的操作起到警示作用,例如永久刪除一則訊息或一張圖片。指定之後它會以紅色高亮顯示:
actionSheet.destructiveButtonIndex = 1;
與導覽列類似,action sheet 也提供三種風格:
UIActionSheetStyleDefault // 預設風格:灰色背景配白色文字 UIActionSheetStyleBlackTranslucent // 半透明黑色背景,白色文字 UIActionSheetStyleBlackOpaque // 純黑背景,白色文字 // 用法 actionSheet.actionSheetStyle = UIActionSheetStyleBlackOpaque;
UIActionSheet 在 iOS 8 之後已被標記為廢棄,官方建議改用 UIAlertController 並指定 UIAlertControllerStyleActionSheet。新專案請直接採用新 API,除了避免警告,也能拿到更好的深色模式與動態字型支援。