UIActionSheet 是 iOS 上從底部彈出的選項清單,可以一次放多個項目,並為每一項處理點擊事件,常用於「拍攝/從相簿選取」這類操作分流。
開啟 Xcode 4.3.2,建立一個 Single View Application,在 xib 上拖一個 button,用來觸發 sheet。
在 .h 檔的 @interface 行尾加上 <UIActionSheetDelegate>。協議相當於 Java 的介面,宣告之後實作其中的方法即可。
@interface sheetviewViewController : UIViewController <UIActionSheetDelegate> @end
把 button 命名為 showSheetView,按住 Ctrl 拖曳到 .h 檔建立 Action 映射,事件類型選 Action,命名為 showSheet。
- (IBAction)showSheet:(id)sender {
UIActionSheet *actionSheet = [[UIActionSheet alloc]
initWithTitle:@"title,nil時不顯示"
delegate:self
cancelButtonTitle:@"取消"
destructiveButtonTitle:@"確定"
otherButtonTitles:@"第一項", @"第二項", nil];
actionSheet.actionSheetStyle = UIActionSheetStyleBlackOpaque;
[actionSheet showInView:self.view];
}
參數說明:cancelButtonTitle 與 destructiveButtonTitle 是系統預留的兩個位置,前者是取消、後者是紅色的破壞性操作;otherButtonTitles 接你要自訂的項目,最後一個參數必須是 nil 作為結束標記;showInView: 表示在目前 view 上顯示,另有 showFromToolbar:、showFromTabBar: 等方法可視版面選用。
先封裝一個提示方法,用 UIAlertView 把結果顯示出來,方便觀察:
-(void)showAlert:(NSString *)msg {
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle:@"Action Sheet選擇項"
message:msg
delegate:self
cancelButtonTitle:@"確定"
otherButtonTitles: nil];
[alert show];
}
接著實作委派方法,用 buttonIndex 判斷被點的是哪一項:
-(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:@"取消"];
}
}
委派協議還有其他可選方法,例如 actionSheetCancel:、willDismissWithButtonIndex:、didDismissWithButtonIndex:,需要處理取消或消失時的收尾就實作它們。
buttonIndex 的順序依 addButtonWithTitle:/初始化時傳入參數的先後而定,取消按鈕與破壞性按鈕不一定排在最前,因此正式專案裡建議用列舉常數對照 index,別寫死數字。另外 iOS 8 之後 UIAlertView 與 UIActionSheet 已被標記為廢棄,新專案請改用 UIAlertController 的 actionSheet 樣式。