Actionsheet和AlertView的使用

来源:互联网 发布:网络创业 编辑:程序博客网 时间:2024/05/06 21:01

AlertView是警告框,用于给用户以警告或者是提示,最多有两个按钮,超过两个按钮应该使用操作表Actionsheet。由于在IOS中,警告框是“模态”(不关闭它就不能做别的事情,Actionsheet也是如此,IOS是以MVC:模态--视图--控制为基理的)。接下来我将讲解今天所完成的例子:

1,从对象库中向故事版拖入两个button控件,分别命名为:test警告框,test操作表。然后将这两个控件设置为动作,.h文件中相关代码如下:

#import  <UIKit/UIKit.h>


@interface ViewController :UIViewController<UIAlertViewDelegate,UIActionSheetDelegate>

- (IBAction)testAlertView:(id)sender;

- (IBAction)testActionSheet:(id)sender;


@end


备注:最开始生成这个工程的时候,第一行是#import"ViewController.h",当我们在@interface ViewController后添加协议:UIViewController<UIAlertViewDelegate,UIActionSheetDelegate>时,就会出现报错:Duplicate interface definition for class “ViewController”(重复的接口定义类);

2,完善testAlertView方法和testActionSheet方法:

2.1.1,testAlertView方法:


- (IBAction)testAlertView:(id)sender {

    UIAlertView *alertView=[[UIAlertViewalloc] initWithTitle:@"Alert"message:@"It`s dangerous!Do you want to continue?" delegate:selfcancelButtonTitle:@"NO"otherButtonTitles:nil];

    [alertView addButtonWithTitle:@"YES"];   //添加一个“YES”按钮

    [alertViewshow];                         

    

}


备注:delegate参数在本例中设置为self,即警告框的委托对象时当前的视图控制器(ViewControll),cancelButtonTitle参数用于设置“取消”按钮的标题,它是警告框的左按钮,ohterButtonTitles参数是其他按钮,为一个字符串数组,以nil结尾。


效果图:




2.1.2在控制台显示所按的按钮,我们可以添加如下代码:

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{


    NSLog (@"the alertView buttonIndex=%i",buttonIndex);

}

效果图:

备注:clickedButtonAtIndex参数是按钮索引,cancelButton按钮的索引是0,从左到右依次是1,2,3。。。

2.2.1,testActionsheet方法:


- (IBAction)testActionSheet:(id)sender {

    UIActionSheet *actionsheet=[[UIActionSheetalloc]initWithTitle:nildelegate:selfcancelButtonTitle:@"取消"destructiveButtonTitle:@"破坏性按钮"otherButtonTitles:@"Facebook",@"新浪微博",nil];

    //[actionsheet addButtonWithTitle:@"Wechat"];

    actionsheet.actionSheetStyle=UIActionSheetStyleAutomatic;

    [actionsheetshowInView:self.view];

    

}


效果图:


备注:如果我们没有将 //[actionsheet addButtonWithTitle:@"Wechat"];注掉,那么显示效果如下,我们发现添加的按钮都在“取消”按钮之后,


2.2.2,同样,我们如果想在控制台显示点击的按钮,可以添加如下代码:

-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{


    NSLog(@"the actionsheet buttonIndex=%i",buttonIndex);

    

}

效果图:

  另外,在网上搜到一篇比较详细介绍AlertView的帖子,可供我们参考:http://www.chengxuyuans.com/iPhone_IOS/61772.html。


0 0
原创粉丝点击