1. 程式人生 > >IOS中的通知--操作表ActionSheet和警報AlertView

IOS中的通知--操作表ActionSheet和警報AlertView

轉自holydancer的CSDN專欄,原文地址:http://blog.csdn.net/holydancer/article/details/7404302

今天介紹兩種控制元件,用來向用戶提供通知並供選擇,ActionSheet從底部彈出,可以顯示一系列的按鈕,AlertView是螢幕中間彈出一個對話方塊形式的,類似於android的dialog,並且可以在AlertView上新增一個TextField用來輸入密碼或者別的內容。具體看程式碼,我們還開啟昨天的程式碼,上面我們昨天設定了一個button控制元件,今天我們先用這個button控制元件來響應一個ActionSheet:

昨天的button是空白的,我們先開啟xib檔案,編輯title為“點選調出ActionSheet",然後在viewController中建立一個操作方法clickButton,將該button的touch up inside行為與該方法相關聯,然後在該方法中如下編輯:

  1. - (IBAction)clickButton:(id)sender {  
  2.     UIActionSheet *myActionSheet=[[UIActionSheet alloc]initWithTitle:@"標題" delegate:self cancelButtonTitle:@"取消鍵" destructiveButtonTitle:@"毀滅鍵" otherButtonTitles:@"額外加鍵", nil];  
  3.     //這樣就建立了一個UIActionSheet物件,如果要多加按鈕的話在nil前面直接加就行,記得用逗號隔開。  
  4.     //下面是顯示,注意ActioinSheet是出現在底部的,是附加在當前的View上的,所以我們用showInView方法  
  5.     [myActionSheet showInView:self.view];  
  6. }  

這時,ActionSheet已經可以顯示出效果了:


但是這個ActionSheet是沒有按鍵響應的,如果細心的話會發現上面我們在建立ActionSheet物件時有一個delegate引數我們給了self,這個引數就是指要響應ActionSheet選擇事件的物件,響應ActionSheet事件需要實現一個協議UIActionSheetDelegate,我們寫了self,那麼我們就在viewController裡實現這個協議,然後重寫這個協議中的actionSheet:didDismissWithButtonIndex:方法,用該方法來捕捉actionSheet的響應事件。看程式碼:

在viewController.h宣告時加上這樣

  1. @interface ViewController : UIViewController<UIActionSheetDelegate>  

在.m檔案裡面新增協議方法:
  1. -(void)actionSheet:(UIActionSheet *)actionSheet didDismissWithButtonIndex:(NSInteger)buttonIndex  
  2. {  
  3.     if (buttonIndex==[actionSheet destructiveButtonIndex])   
  4.         //這裡捕捉“毀滅鍵”,其實該鍵的index是0,從上到下從0開始,稱之為毀滅是因為是紅的  
  5.     {  
  6.         //點選該鍵後我們再彈出一個AlertView  
  7.         UIAlertView *myAlertView = [[UIAlertView alloc] initWithTitle:@"AlertView的標題" message:@"我是一個AlertView" delegate:self cancelButtonTitle:@"取消鍵" otherButtonTitles:@"隨手加", nil];  
  8.         //這是彈出的一個與當前View無關的,所以顯示不用showIn,直接show  
  9.         [myAlertView show];  
  10.     }  
  11. }  

該方法捕捉了我們點選ActionSheet中的毀滅鍵後的事件:生成了一個AlertView並顯示,如下


我們發現AlertView的生成方法和ActionSheet真的很像,不同的只是一個是show,一個是showIn,程式碼中我們的AlertView的兩個按鍵我們還沒有進行處理,同ActionSheet的按鍵響應幾乎一樣,我們需要將當前的類(self)實現一個協議,<UIAlertViewDelegate>

  1. @interface ViewController : UIViewController<UIActionSheetDelegate,UIAlertViewDelegate>  
在.m檔案中的響應方法為:
  1. -(void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex  
  2. {  
  3.     //這裡你自己補充吧,你可以再彈出一個ActionSheet或者什麼,whatever,who cares?  
  4. }