UIAlertController 封装(block 一行代码回调)

iOS 开发中,最常用的一个控件就是 弹窗提醒控件。iOS8之后,UIAlertController 的 block 回调方式,无疑比之前 UIAlertView的delegate 方式便捷许多。但还是需要多个步骤:

  1. 创建 alertController
  2. 创建并添加 alertAction, 可能要创建多个
  3. present 推出弹窗,并在 block 回调中进行对应操作。
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"标题" message:@"内容" preferredStyle:UIAlertControllerStyleAlert];
    
    // creat actions
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        NSLog(@"@@~ 点击了“确认”按钮 ~@@");
    }];
    
    UIAlertAction *confirmAction = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSLog(@"@@~ 点击了“确认”按钮 ~@@");
    }];
    
    // add actons
    [alertController addAction:cancelAction];
    [alertController addAction:confirmAction];
    
    // present
    [self presentViewController:alertController animated:YES completion:nil];

如上,代码量其实并不低。所以呢,当然要进行封装,再封装。

有鉴于此,我封装了个相应的工具类,一句代码调用,如下:
    /** 单按键 */
    [JHSysAlertUtil presentAlertViewWithTitle:@"标题" message:@"This a message" confirmTitle:@"确定" handler:^{
        NSLog(@"@@  This is just a log O(∩_∩)O~ @@");
    }];
    
    /** 双按键 */
    [JHSysAlertUtil presentAlertViewWithTitle:@"标题" message:@"This is message" cancelTitle:@"取消" defaultTitle:@"确认" distinct: YES cancel:^{
        NSLog(@"@@~ 取消 ~@@");
    } confirm:^{
        NSLog(@"@@~ 确认 ~@@");
    }];
    
    /** Alert  任意多个按键 返回选中的 buttonIndex 和 buttonTitle */
    [JHSysAlertUtil presentAlertWithTitle:@"标题" message:@"This is message" actionTitles:@[@"first", @"second", @"third"] preferredStyle:UIAlertControllerStyleActionSheet handler:^(NSUInteger buttonIndex, NSString *buttonTitle) {
        NSLog(@"@@~~ : %lu, %@", (unsigned long)buttonIndex, buttonTitle);
    }];

最为有用的应当是第三种用法,可选 alertView 和 actionSheet 两种模式,回调中可以获取选中按键的下标以及标题。

原理:其实很简单,无非是对 block 语法的一种简单应用。 具体见 demo 中的注释吧。

后续会写一下自己对block 的理解。自从一遇 block,从此 delegate 是路人。(觉得代理麻烦的同学,强烈建议学习一下 block)

点此下载源码

附上一篇介绍UIAlertController的文章链接: 在iOS 8中使用UIAlertController

刚开始写 blog,不足之处,欢迎大家留言交流,无论是 iOS的理解运用,还是行文语法。O(∩_∩)O哈哈~

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 12,245评论 4 61
  • 六顶思考帽的思维方法已在世界各地得到广泛应用。这种方法,使我们关注的焦点从‘是什么?’变成了‘能够怎样?’以及如何...
    美淇阅读 453评论 0 0
  • 前端里移动端到底比pc端多哪些知识,为啥面试时好多公司都问h5水平如何? 我做过几年的web前端开发,就简单谈谈自...
    横冲直撞666阅读 1,241评论 0 3
  • 记得大学时候选修《影视节目赏析》的课上,老师在给我们播放《泰坦尼克号》时说:正是因为杰克跟露丝最后走不到一...
    辛馨阅读 303评论 0 0