UIAlertController在UIView环境下的使用

序言:UIAlertController在iOS8.0提出,目的是替换UIAlertView、UIActionSheet,这两个控件分别在9.0和8.3废弃。后两者是delegate响应选择按钮的点击事件,而UIAlertController是用block语法来实现。
今天我将的主题源于:UIAlertView、UIActionSheet继承自UIView,而UIAlertController是继承自UIViewController,所以当UIAlertController应用在UIView环境中(代码写在UI的子类中),则跟以前大大的不同。
UIAlertController弹出只能通过present,也就是说必须有控制器,这样才能present。
一个简单且实用的方法就是,新建一个UIViewController。
talk is cheap ,show you the code!

{
    NSString * string;//这里为了说明定义的,无实际意义
    UIViewController *viewCTL = [[UIViewController alloc]init];//临时UIViewController,从它这里present UIAlertController
    [self addSubview:viewCTL.view];//这句话很重要,即把UIViewController的view添加到当前视图或者UIWindow
    //以下为UIAlertController的构造和配置
    UIAlertController *alertCTL = [UIAlertController alertControllerWithTitle:string message:nil preferredStyle:UIAlertControllerStyleAlert];
    __weak typeof(alertCTL) kAlertCTL = alertCTL;
    [alertCTL addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        [textField setSecureTextEntry:YES];
        [textField setPlaceholder:string];
    }];
    [alertCTL addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        [textField setSecureTextEntry:YES];
        [textField setPlaceholder:string];
    }];
    UIAlertAction *alertAction1 = [UIAlertAction actionWithTitle:string style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
        //处理点击取消按钮
        [viewCTL.view removeFromSuperview];
    }];
    UIAlertAction *alertAction2 = [UIAlertAction actionWithTitle:string style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        //处理点击确定按钮
        [viewCTL.view removeFromSuperview];
    }];
    
    [alertCTL addAction:alertAction1];
    [alertCTL addAction:alertAction2];
    [viewCTL presentViewController:alertCTL animated:YES completion:nil];//弹出该UIAlertController
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 14,780评论 4 61
  • 一、安装nginx sudo apt-get install nginx 安装完成后查看一下:nginx -v 说...
    limx阅读 4,140评论 0 0
  • 早上叫茜茜起床,她拖拖拉拉的,起来后也是慢吞吞的,我就生气了,冲她吼了两句,很显然,孩子是害怕我骂他,不情愿的去洗...
    天马1004阅读 1,607评论 0 0
  • 或许是出于母性的本能,或许是因为自己已经开始在慢慢变老。这一学年来,每次在QQ空间,或是Q群里给你们发消息时,总是...
    老草阅读 2,790评论 11 9

友情链接更多精彩内容