Actionsheet和AlertView的使用

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=[[UIAlertView alloc] initWithTitle:@"Alert" message:@"It`s dangerous!Do you want to continue?"  delegate:self cancelButtonTitle:@"NO"otherButtonTitles:nil];

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

    [alertView show];                         

    

}


备注: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=[[UIActionSheet alloc]initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:@"破坏性按钮" otherButtonTitles:@"Facebook",@"新浪微博",nil];

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

    actionsheet.actionSheetStyle=UIActionSheetStyleAutomatic;

    [actionsheet showInView: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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值