iOS程序中的Action Sheet就像Windows中的 「肯定-取消」對話框同樣,用於強制用戶進行選擇。當用戶將要進行的操做具備必定危險時,經常使用Action Sheet對用戶進行危險提示,這樣,用戶有機會進行取消操做。code
Alert至關於Windows中的Messagebox,跟Action Sheet也是相似的。不一樣的是,Alert能夠只有一個選擇項,而Action Sheet卻至少要兩個選項。事件
跟以往同樣,假設咱們已經創建了一個Single View Application,打開其中的ViewController.xib文件。it
首先,咱們先放一個Button在View上面,咱們要的效果是:點擊Button打開一個Action Sheet,接下來點擊Action Sheet的一個按鈕,彈出一個Alert。io
一、首先,要在ViewController.h中添加代碼,使其實現一個協議。添加代碼的地方在@interface那行的最後添加<UIActionSheetDelegate>,添加以後那行代碼是:class
@interface ViewController : UIViewController<UIActionSheetDelegate>
二、拖放一個Button到View上,將Button的名稱改成 Do something。sed
三、爲這個Button創建Action映射,映射到ViewController.h中,事件類型默認,名稱爲 buttonPressed。程序
四、在ViewController.m中找到buttonPressed方法,添加如下代碼:方法
- (IBAction)buttonPressed:(id)sender { UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"Are you sure?" delegate:self cancelButtonTitle:@"No Way!" destructiveButtonTitle:@"Yes, I'm sure!" otherButtonTitles:nil]; [actionSheet showInView:self.view]; }
如上面代碼所示,建立一個Action Sheet須要多個參數:im
(1)initWithTitle:設置標題,將會顯示在Action Sheet的頂部協議
(2)delegate:設置Action Sheet的委託。當Action Sheet的一個按鈕被按下後,它的delegate將會被通知,而且會執行這個delegate的actionSheet: didDismissWithButtonIndex方法將會執行。這裏,咱們將delegate設成self,這樣能夠保證執行咱們本身在ViewController.m寫的actionSheet: didDismissWithButtonIndex方法
(3)cancelButtonTitle:設置取消按鈕的標題,這個取消按鈕將會顯示在Action Sheet的最下邊
(4)destructiveButtonTitle:設置第一個肯定按鈕的標題,這個按鈕能夠理解成:"好的,繼續"
(5)otherButtonTitles:能夠設置任意多的肯定按鈕,想要添加兩個按鈕,能夠寫成:
otherButtonTitles: @」New Button 1」, @」New Button 2」, nil
注意到,最後一個參數要是nil
[actionSheet showInView:self.view]這條語句用來顯示Action Sheet,準確的說,這條語句是給這個Action Sheet設置Parent,而這個Parent必須是一個View,而且是當前正在顯示的View。
五、而後,咱們在ViewController.m中添加一個方法,完整代碼爲:
- (void)actionSheet:(UIActionSheet *)actionSheet didDismissWithButtonIndex:(NSInteger)buttonIndex { if (buttonIndex != [actionSheet cancelButtonIndex]) { NSString *msg = nil; msg = @"You can breathe easy, everything went OK."; UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Something was done" message:msg delegate:self cancelButtonTitle:@"Prew!" otherButtonTitles: nil]; [alert show]; } }
這個方法就是咱們輕觸了Action Sheet以後將會執行的代碼。因爲以前咱們將Action Sheet的delegate設成self,於是這個方法將會被調用,這個方法的參數buttonIndex表示用戶所輕觸的按鈕的編號,按鈕編號是從上到下,從0開始的,例如,"Yes, I'm sure!"這個按鈕的編號是0,由於它是第一個肯定按鈕,取消按鈕是顯示在最下邊的。取消按鈕的編號,能夠經過[actionSheet cancelButtonIndex]直接得到。
構造一個Alert也要填寫不少參數:
(1)initWithTitle:設置標題,將會顯示在Alert的頂部
(2)message:設置提示消息內容
(3)delegate:設置Alert的委託。這裏,咱們設成self
(4)cancelButtonTitle:設置取消按鈕的標題
(5)otherButtonTitles:與Action Sheet相似
[alert show]這條語句用來顯示Alert。
六、運行一下,看看效果吧: