歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> iOS開發教程之UIActionSheet的使用

iOS開發教程之UIActionSheet的使用

日期:2017/3/1 10:14:53   编辑:Linux編程

UIActionSheet是在IOS彈出的選擇按鈕項,可以添加多項,並為每項添加點擊事件。

為了快速完成這例子,我們打開Xcode 4.3.2, 先建立一個single view application。然後再xib文件添加一個button,用來彈出sheet view。

1、首先在.h文件中實現協議,加代碼的地方在@interface那行的最後添加<UIActionSheetDelegate>,協議相當於java裡的接口,實現協議裡的方法。

  1. @interface sheetviewViewController : UIViewController<UIActionSheetDelegate>
  2. @end

2、添加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. }

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:msg
  5. delegate:self
  6. 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. - (void)actionSheetCancel:(UIActionSheet *)actionSheet{
  14. }
  15. -(void)actionSheet:(UIActionSheet *)actionSheet didDismissWithButtonIndex:(NSInteger)buttonIndex{
  16. }
  17. -(void)actionSheet:(UIActionSheet *)actionSheet willDismissWithButtonIndex:(NSInteger)buttonIndex{
  18. }

可以看到 buttonIndex 是對應的項的索引。

看到那個紅色的按鈕沒?那是ActionSheet支持的一種所謂的銷毀按鈕,對某戶的某個動作起到警示作用,

Copyright © Linux教程網 All Rights Reserved