iOS开发--自定义UIAlertController

在日常开发中,我们往往要满足各种需求,自定义AlertController颜色等,也算其一,那么,如何来自定义系统控件呢?下面提供了一种自定义UIAlertController的方式:

Tips: 通过KVO,我们可以给AlertController设置自定义attributedTitle,和attributedMessag、还可以给按钮设置图片等;同时,我们还可以通过设置TintColor的方式来改变按钮颜色


            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Test" message:@"" preferredStyle:UIAlertControllerStyleAlert];
            alert.view.tintColor = [UIColor redColor];
            
            UIAlertAction *action = [UIAlertAction actionWithTitle:@"Ok" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                
            }];
            //Add image 这里可以给button添加图片
            UIImage *accessoryImage = [UIImage imageNamed:@"Icon_60"];
            accessoryImage = [accessoryImage imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
            [action setValue:accessoryImage forKey:@"image"];

            
            [alert addAction:action];

            UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                
            }];
            [alert addAction:action2];

            
            //Custom Title
            NSMutableAttributedString *hogan = [[NSMutableAttributedString alloc] initWithString:@"Presenting the great... Hulk Hogan!"];
            [hogan addAttribute:NSFontAttributeName
                          value:[UIFont systemFontOfSize:20]
                          range:NSMakeRange(24, 11)];
            [alert setValue:hogan forKey:@"attributedTitle"];
            [self presentViewController:alert animated:true completion:^{
                
            }];
            alert.view.tintColor = [UIColor orangeColor]; //修复IOS9 tintColor无法修改的问题
            
            break;

参考: https://github.com/devSC/iOS-Runtime-Headers/blob/master/Frameworks/UIKit.framework/UIAlertController.h

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值