iOS经典讲解之iOS8新特性UIAlertController


苹果秋季产品发布会刚刚结束,并且刚刚发布iOS9正式版,伴随着新产品和新系统,可以体验用户体验带来的快感之外。对于我们程序员来说最重要的,并不是这些,而是又有一大堆的方法被弃用,随之一些新方法加入,我们又要默默的点一支烟好好的学习一下了,谁让我们是攻城狮那。今天来介绍一下iOS8之后的新特性UIAlertController,大家看是不是很眼熟,没错它就是今天的主角,它也是iOS9被弃用方法的替代者,它替代的是UIAlertView和UIActionSheet。

先介绍一下即将退出历史舞台的的UIAlertView和UIAlertAction,它们两个是iOS2出现的控件,一直延用至今,在iOS8已经不推荐使用它们,同时出现了替代他们的UIAlertController,在iOS9将彻底弃用它们。UIAlertController与它们相比有相似的地方同时也有区别,使用更加方便和灵活。


    //UIAlertController初始化方法使用便利构造器方法更加方便并且初始化方法中不涉及按钮的配置,因为他有独立的一个类UIAlertAction来配置它的按钮
    //样式preferredStyle:有两个值分别是UIAlertControllerStyleActionSheet|UIAlertControllerStyleAlert分别是之前的UIActionSheet样式和UIAlertView样式
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:@"信息" preferredStyle:UIAlertControllerStyleAlert];
    
    // 同样也可以给其添加按钮 用其独立的类UIAlertAction创建按钮,和UIAlertView相似如果添加两个以上的按钮他会竖排显示
    //弃用了UIAlertView和UIActionSheet的delegate这种方式 而是采用更简单的 完成时回调
    //handler:通过回调方法处理点击事件替代原来的代理方法,更加方便灵活
    //style:(UIAlertActionStyleDefault)按钮样式,需要注意一点的是UIAlertActionStyleCancel样式的按钮只能添加一个,如果添加一个以上会抛出异常
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"ok" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction *action) {
        // do something ...
        NSLog(@"%@", action.title);
    }];
    // 将按钮添加到alertController
    [alertController addAction:okAction];
    
    //创建按钮
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"cancel" style:(UIAlertActionStyleCancel) handler:^(UIAlertAction *action) {
        // do something ...
        NSLog(@"%@", action.title);
    }];
    [alertController addAction:cancelAction];
    
    
    // 添加textField
    // 原则上讲,你可以添加无限个TextField,并且每个的样式都可以自定义,UITextField具有的特性,这里都具有
    //注意:在UIAlertControllerStyleActionSheet样式下是不可以添加textField的 否则会抛出异常
    [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
        // 设置任何样式的TextField
        textField.placeholder = @"用户名";
    }];
    [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
        // 设置任何样式的TextField
        textField.placeholder = @"密码";
        textField.secureTextEntry = YES;
    }];
    
    // 取出添加上的textField和action
    NSArray *textFields = alertController.textFields;
    NSArray *actions = alertController.actions;
    
    // 显示
    // 因为UIAlertController继承于UIViewController所以它具备其父类的特性,因此它的显示是通过模态方法显示的
    [self presentViewController:alertController animated:YES completion:nil];
    
    // 注意:UIAlertController通过block处理按钮点击事件和设置textField,当里面用的self的时候要注意用__block修饰避免出现循环引用的问题。


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值