美文网首页IOS收藏技术重塑demo
用runtime自定义UIAlertView的字体大小和颜色

用runtime自定义UIAlertView的字体大小和颜色

作者: 顾意_null | 来源:发表于2016-04-27 18:30 被阅读2484次

在公司app版本发布前两小时,产品突然说觉得UIAlertView上的字体太小想再改粗点,WTF!最讨厌这种临时变卦的产品,好吧那就做一做。首先想到系统自带的UIAlertView好像不能改变字体的大小和颜色(虽然苹果公司现在推荐用UIAlertViewController,但是要iOS8以上,所以还是用的UIAlertView)所以想着自定义写一个AlertView但是想想好麻烦啊本来都打算发布可以歇一歇了,想到要不试试用runtime动态把属性替换掉,so let's start.
先写个demo,


先把这个设置设成no,本来是想着替换方法,不过后来其实没用过objc_msgsend方法。。。然后导入runtime头文件

#import <objc/runtime.h>

demo里为了随大潮用了UIAlertViewController😂
首先遍历一遍UIAlertViewController的属性

unsigned int count = 0;
Ivar *property = class_copyIvarList([UIAlertController class], &count);
for (int i = 0; i < count; i++) {
    Ivar var = property[i];
    const char *name = ivar_getName(var);
    const char *type = ivar_getTypeEncoding(var);
    NSLog(@"%s =============== %s",name,type);
}

果然从打印的属性中找到了想要的东西


按这两个名字看肯定有用!第一个就是UIAlertViewController的message属性,第二个看样子就是用来改变这个message的好东西了,所以尝试修改了一下
 Ivar message = property[2];    
/**
  *  字体修改
  */
UIFont *big = [UIFont systemFontOfSize:25];
UIFont *small = [UIFont systemFontOfSize:18];
UIColor *red = [UIColor redColor];
UIColor *blue = [UIColor blueColor];
NSMutableAttributedString *str = [[NSMutableAttributedString alloc]initWithString:@"hello world" attributes:@{NSFontAttributeName:big,
NSForegroundColorAttributeName:red}];
[str setAttributes:@{NSFontAttributeName:small} range:NSMakeRange(0, 2)];
[str setAttributes:@{NSForegroundColorAttributeName:blue} range:NSMakeRange(0, 4)];

//最后把message内容替换掉
object_setIvar(_alert, message, str);

运行一下,bingo~


demo地址在这儿,runtime的方法网上有很多就不解释了:)其实最后我没有改,我跟产品说来不及做不来,为了捍卫开发的尊严:)

相关文章

网友评论

本文标题:用runtime自定义UIAlertView的字体大小和颜色

本文链接:https://www.haomeiwen.com/subject/divcrttx.html