【转】iOS开发6:UIActionSheet与UIAlertView
原文: http://my.oschina.net/plumsoft/blog/42763
iOS程序中的Action Sheet就像Windows中的 “確定-取消”對話框一樣,用于強制用戶進行選擇。當用戶將要進行的操作具有一定危險時,常常使用Action Sheet對用戶進行危險提示,這樣,用戶有機會進行取消操作。
Alert相當于Windows中的Messagebox,跟Action Sheet也是類似的。不同的是,Alert可以只有一個選擇項,而Action Sheet卻至少要兩個選項。
跟以往一樣,假設我們已經建立了一個Single View Application,打開其中的ViewController.xib文件。
首先,我們先放一個Button在View上面,我們要的效果是:點擊Button打開一個Action Sheet,接下來點擊Action Sheet的一個按鈕,彈出一個Alert。
1、首先,要在ViewController.h中添加代碼,使其實現一個協議。添加代碼的地方在@interface那行的最后添加<UIActionSheetDelegate>,添加之后那行代碼是:
@interface ViewController : UIViewController<UIActionSheetDelegate>2、拖放一個Button到View上,將Button的名稱改為 Do something。
3、為這個Button建立Action映射,映射到ViewController.h中,事件類型默認,名稱為 buttonPressed。
4、在ViewController.m中找到buttonPressed方法,添加以下代碼:
- (IBAction)buttonPressed:(id)sender {UIActionSheet *actionSheet = [[UIActionSheet alloc]initWithTitle:@"Are you sure?"delegate:selfcancelButtonTitle:@"No Way!"destructiveButtonTitle:@"Yes, I'm sure!"otherButtonTitles:nil];[actionSheet showInView:self.view]; }如上面代碼所示,創建一個Action Sheet需要多個參數:
(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。
5、然后,我們在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:msgdelegate:selfcancelButtonTitle:@"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。
6、運行一下,看看效果吧:
?
?注明: 作者說Action Sheet卻至少要兩個選項, 也可以有一個吧,
UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"UIActionSheet <title>"
????????????????? delegate:self cancelButtonTitle:nil destructiveButtonTitle:@"OK" otherButtonTitles:nil];
轉載于:https://www.cnblogs.com/A--G/p/4717220.html
總結
以上是生活随笔為你收集整理的【转】iOS开发6:UIActionSheet与UIAlertView的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Zepto 与 jQuery 的区别 小
- 下一篇: 1121