標籤:des style blog http color os io 使用 java
UIActionSheet是在iOS彈出的選擇按鈕項,可以添加多項,並為每項添加點擊事件。
為了快速完成這例子,我們開啟Xcode , 先建立一個single view application。然後再xib檔案添加一個button,用來彈出sheet view。
1、首先在.h檔案中實現協議
加代碼的地方在@interface那行的最後添加<UIActionSheetDelegate>,協議相當於java裡的介面,實現協議裡的方法。
@interface sheetviewViewController : UIViewController<UIActionSheetDelegate>
@end2、添加button,命名button為showSheetView.3、為button建立Action映射,映射到.h檔案上,事件類型為Action ,命名為showSheet。4、在.m檔案上添加點擊事件代碼
圖的效果是這樣的:
1 - (IBAction)showSheet:(id)sender { 2 UIActionSheet *actionSheet = [[UIActionSheet alloc] 3 initWithTitle:@"title,nil時不顯示" 4 delegate:self 5 cancelButtonTitle:@"取消" 6 destructiveButtonTitle:@"確定" 7 otherButtonTitles:@"第一項", @"第二項",nil]; 8 actionSheet.actionSheetStyle = UIActionSheetStyleBlackOpaque; 9 [actionSheet showInView:self.view];10 }11 actionSheet.actionSheetStyle = UIActionSheetStyleBlackOpaque;//設定樣式
參數解釋:
cancelButtonTitle destructiveButtonTitle是系統自動的兩項。
otherButtonTitles是自己定義的項,注意,最後一個參數要是nil。
[actionSheet showInView:self.view];這行語句的意思是在當前view顯示Action sheet。當然還可以用其他方法顯示Action sheet。
對應上面的圖和代碼,一目瞭然了把
5、接下來我們怎麼相應Action Sheet的選項的事件呢?
實現協議裡的方法。為了能看出點擊Action sheet每一項的效果,我們加入UIAlertView來做資訊顯示。下面是封裝的一個方法,傳入對應的資訊,在UIAlertView顯示對應的資訊。
1 -(void)showAlert:(NSString *)msg {2 UIAlertView *alert = [[UIAlertView alloc]3 initWithTitle:@"Action Sheet選擇項"4 message:msg5 delegate:self6 cancelButtonTitle:@"確定"7 otherButtonTitles: nil];8 [alert show];9 }
那相應被Action Sheet選項執行的代碼如下:
1 - (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex 2 { 3 if (buttonIndex == 0) { 4 [self showAlert:@"確定"]; 5 }else if (buttonIndex == 1) { 6 [self showAlert:@"第一項"]; 7 }else if(buttonIndex == 2) { 8 [self showAlert:@"第二項"]; 9 }else if(buttonIndex == 3) {10 [self showAlert:@"取消"];11 } 12 13 }14 - (void)actionSheetCancel:(UIActionSheet *)actionSheet{ 15 16 } 17 -(void)actionSheet:(UIActionSheet *)actionSheet didDismissWithButtonIndex:(NSInteger)buttonIndex{ 18 19 } 20 -(void)actionSheet:(UIActionSheet *)actionSheet willDismissWithButtonIndex:(NSInteger)buttonIndex{ 21 22 }
可以看到 buttonIndex 是對應的項的索引。
看到那個紅色的按鈕沒?那是ActionSheet支援的一種所謂的銷毀按鈕,對某戶的某個動作起到警示作用,
比如永久性刪除一條訊息或映像時。如果你指定了一個銷毀按鈕他就會以紅色高亮顯示:
actionSheet.destructiveButtonIndex=1;
與導覽列類似,動作表單也支援三種風格 :
UIActionSheetStyleDefault //預設風格:灰色背景上顯示白色文字
UIActionSheetStyleBlackTranslucent //透明黑色背景,白色文字
UIActionSheetStyleBlackOpaque //純黑背景,白色文字
用法:
actionSheet.actionSheetStyle = UIActionSheetStyleBlackOpaque;//設定樣式
我選sheet 裡的第一項,顯示如下:
6、注意事項
在開發過程中,發現有時候UIActionSheet的最後一項點擊失效,點最後一項的上半地區時有效,這是在特定情況下才會發生,這個情境就是試用了UITabBar的時候才有。解決辦法:
在showView時這樣使用,[actionSheet showInView:[UIApplication sharedApplication].keyWindow];或者[sheet showInView:[AppDelegate sharedDelegate].tabBarController.view];這樣就不會發生遮擋現象了。
【IOS】UIActionSheet的使用