UIAlertController 简单修改title以及按钮的字体颜色(block)

欢迎加入 iOS开发QQ群:151133690

本篇内容是对<a href ="http://www.jianshu.com/p/cecd1b4bbf27" > UIAlertController 简单修改title以及按钮的字体颜色 </a>的加强版,对系统UIAlertController类添加Category使用更加简单,同时添加block回调方法

/**
 根据otherActionTitles数组创建UIAlertController

 @param title title
 @param message message
 @param cancelActionTitle 取消Action标题
 @param otherActionTitles 其他Action标题
 @param handle 点击回调 -1 取消Action点击 0~n 其他Action点击
 @return UIAlertController
 */
+(instancetype)alertControllerWithTitle:(NSString *)title message:(NSString *)message cancelActionTitle:(NSString *)cancelActionTitle otherActionTitles:(NSArray<NSString *> *)otherActionTitles handle:(void (^)(NSInteger index))handle;

先来看看效果示例

修改按钮颜色.PNG
修改标题颜色.PNG
修改按钮和标题的颜色.PNG

做法很简单,自己写UIAlertController的Category 别忘了导入头文件,然后复制如下代码到.h 和.m即可.

UIAlertController+Color.h

//
//  UIAlertController+Color.h
//  UIAlertControllerColor
//
//  Created by benben on 16/12/15.
//  Copyright © 2016年 benben. All rights reserved.
//

#import <UIKit/UIKit.h>

@interface UIAlertController (Color)

@property (nonatomic,strong) UIColor *tintColor; /**< 统一按钮样式 不写系统默认的蓝色 */
@property (nonatomic,strong) UIColor *titleColor; /**< 标题的颜色 */
@property (nonatomic,strong) UIColor *messageColor; /**< 信息的颜色 */


/**
 根据otherActionTitles数组创建UIAlertController

 @param title title
 @param message message
 @param cancelActionTitle 取消Action标题
 @param otherActionTitles 其他Action标题
 @param handle 点击回调 -1 取消Action点击 0~n 其他Action点击
 @return UIAlertController
 */
+(instancetype)alertControllerWithTitle:(NSString *)title message:(NSString *)message cancelActionTitle:(NSString *)cancelActionTitle otherActionTitles:(NSArray<NSString *> *)otherActionTitles handle:(void (^)(NSInteger index))handle;

@end

@interface UIAlertAction (Color)

@property (nonatomic,strong) UIColor *textColor; /**< 按钮title字体颜色 */

@end

UIAlertController+Color.m

//
//  UIAlertController+Color.h
//  UIAlertControllerColor
//
//  Created by benben on 16/12/15.
//  Copyright © 2016年 benben. All rights reserved.
//

#import "UIAlertController+Color.h"
#import <objc/runtime.h>

@implementation UIAlertController (Color)

/**
 根据otherActionTitles数组创建UIAlertController
 
 @param title title
 @param message message
 @param cancelActionTitle 取消Action标题
 @param otherActionTitles 其他Action标题
 @param handle 点击回调 -1 取消Action点击 0~n 其他Action点击
 @return UIAlertController
 */
+(instancetype)alertControllerWithTitle:(NSString *)title message:(NSString *)message cancelActionTitle:(NSString *)cancelActionTitle otherActionTitles:(NSArray<NSString *> *)otherActionTitles handle:(void (^)(NSInteger))handle
{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleActionSheet];
    
    //如果有取消按钮
    if (cancelActionTitle) {
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:cancelActionTitle style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
            if (handle) {
                handle(-1);
            }
        }];
        
        [alertController addAction:cancelAction];
    }
    
    if (otherActionTitles.count > 0) {
        
        [otherActionTitles enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            
            UIAlertAction *otherAction = [UIAlertAction actionWithTitle:obj style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                if (handle) {
                    handle(idx);
                }
            }];
            
            [alertController addAction:otherAction];
            
        }];
    }
    
    return alertController;
}

-(void)viewWillLayoutSubviews
{
    [super viewWillLayoutSubviews];
    
    //按钮统一颜色
    if (self.tintColor) {
        for (UIAlertAction *action in self.actions) {
            if (!action.textColor || action.style != UIAlertActionStyleDestructive) {
                action.textColor = self.tintColor;
            }
        }
    }
}

-(UIColor *)tintColor
{
    return objc_getAssociatedObject(self, @selector(tintColor));
}

-(void)setTintColor:(UIColor *)tintColor
{
    
    objc_setAssociatedObject(self, @selector(tintColor), tintColor, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

-(UIColor *)titleColor
{
    return objc_getAssociatedObject(self, @selector(titleColor));
}

-(void)setTitleColor:(UIColor *)titleColor
{
    unsigned int count = 0;
    Ivar *ivars = class_copyIvarList([UIAlertController class], &count);
    for(int i = 0;i < count;i ++){
        
        Ivar ivar = ivars[i];
        NSString *ivarName = [NSString stringWithCString:ivar_getName(ivar) encoding:NSUTF8StringEncoding];

        //标题颜色
        if ([ivarName isEqualToString:@"_attributedTitle"] && self.title && titleColor) {
            
            NSMutableAttributedString *attr = [[NSMutableAttributedString alloc]initWithString:self.title attributes:@{NSForegroundColorAttributeName:titleColor,NSFontAttributeName:[UIFont boldSystemFontOfSize:14.0]}];
            [self setValue:attr forKey:@"attributedTitle"];
        }
    }
    
    free(ivars);
    
    objc_setAssociatedObject(self, @selector(titleColor), titleColor, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

-(UIColor *)messageColor
{
    return objc_getAssociatedObject(self, @selector(messageColor));
}

-(void)setMessageColor:(UIColor *)messageColor
{
    unsigned int count = 0;
    Ivar *ivars = class_copyIvarList([UIAlertController class], &count);
    for(int i = 0;i < count;i ++){
        
        Ivar ivar = ivars[i];
        NSString *ivarName = [NSString stringWithCString:ivar_getName(ivar) encoding:NSUTF8StringEncoding];
    
        //描述颜色
        if ([ivarName isEqualToString:@"_attributedMessage"] && self.message && messageColor) {
            
            NSMutableAttributedString *attr = [[NSMutableAttributedString alloc] initWithString:self.message attributes:@{NSForegroundColorAttributeName:messageColor,NSFontAttributeName:[UIFont systemFontOfSize:14.0]}];
            [self setValue:attr forKey:@"attributedMessage"];
        }
    }
    
    free(ivars);
    
    objc_setAssociatedObject(self, @selector(messageColor), messageColor, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

@end


@implementation UIAlertAction (Color)
-(UIColor *)textColor
{
    return objc_getAssociatedObject(self, @selector(textColor));
}

//按钮标题的字体颜色
-(void)setTextColor:(UIColor *)textColor
{
    if (self.style == UIAlertActionStyleDestructive) {
        return;
    }
    
    unsigned int count = 0;
    Ivar *ivars = class_copyIvarList([UIAlertAction class], &count);
    for(int i =0;i < count;i ++){
        
        Ivar ivar = ivars[i];
        NSString *ivarName = [NSString stringWithCString:ivar_getName(ivar) encoding:NSUTF8StringEncoding];
        
        if ([ivarName isEqualToString:@"_titleTextColor"]) {
            
            [self setValue:textColor forKey:@"titleTextColor"];
        }
    }
    free(ivars);
    
    objc_setAssociatedObject(self, @selector(textColor), textColor, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

@end

用法就很简单了,和系统原生UIAlertController一样

UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"你确定退出吗" message:@"真的要退出吗?" preferredStyle:UIAlertControllerStyleActionSheet];
    
    alertController.titleColor = [UIColor redColor];//修改title的颜色
    alertController.messageColor = [UIColor yellowColor]; //修改message的颜色
    
    alertController.tintColor = [UIColor redColor]; //全局修改Action的颜色 -- 当然你也可以单独修改某一个Action的颜色 看下面👇
    
    //添加返回按钮
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"我不想退出" style:UIAlertActionStyleCancel handler:nil];
    [alertController addAction:cancel];
    
    cancel.textColor = [UIColor redColor]; //单个修改Action的颜色
    
    //添加确定退出按钮
    UIAlertAction *alertAction = [UIAlertAction actionWithTitle:@"退出" style:UIAlertActionStyleDefault handler:nil];
    [alertController addAction:alertAction];
    
    [self presentViewController:alertController animated:YES completion:nil];

如果你比较懒 那么我推荐你这么使用

    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"我是标题" message:@"我是message" cancelActionTitle:@"我是取消按钮" otherActionTitles:@[@"title1",@"title2",@"title3"] handle:^(NSInteger index) {
        
        //Action点击回调
        //注意 cancelAction index 为 -1,
        // otherAction index为 otherActionTitles数组下标
        
    }];
    alertController.titleColor = [UIColor redColor];//修改title的颜色
    alertController.messageColor = [UIColor yellowColor]; //修改message的颜色
    alertController.tintColor = [UIColor redColor]; //全局修改Action的颜色
    //注意 该方法 不能单独设置 某一个Action的颜色 只能修改全部
    
    alertController.tintColor = [UIColor redColor];
    [self presentViewController:alertController animated:YES completion:nil];

好了 ,就这些了...

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,219评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,363评论 1 293
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,933评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,020评论 0 206
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,400评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,640评论 1 219
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,896评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,597评论 0 199
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,327评论 1 244
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,581评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,072评论 1 261
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,399评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,054评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,083评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,849评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,672评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,585评论 2 270

推荐阅读更多精彩内容