在公司app版本發(fā)布前兩小時(shí),產(chǎn)品突然說覺得UIAlertView上的字體太小想再改粗點(diǎn),WTF!最討厭這種臨時(shí)變卦的產(chǎn)品,好吧那就做一做。首先想到系統(tǒng)自帶的UIAlertView好像不能改變字體的大小和顏色(雖然蘋果公司現(xiàn)在推薦用UIAlertViewController,但是要iOS8以上,所以還是用的UIAlertView)所以想著自定義寫一個(gè)AlertView但是想想好麻煩啊本來都打算發(fā)布可以歇一歇了,想到要不試試用runtime動(dòng)態(tài)把屬性替換掉,so let's start.
先寫個(gè)demo,

先把這個(gè)設(shè)置設(shè)成no,本來是想著替換方法,不過后來其實(shí)沒用過objc_msgsend方法。。。然后導(dǎo)入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);
}
果然從打印的屬性中找到了想要的東西

按這兩個(gè)名字看肯定有用!第一個(gè)就是UIAlertViewController的message屬性,第二個(gè)看樣子就是用來改變這個(gè)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內(nèi)容替換掉
object_setIvar(_alert, message, str);
運(yùn)行一下,bingo~

demo地址在這兒,runtime的方法網(wǎng)上有很多就不解釋了:)其實(shí)最后我沒有改,我跟產(chǎn)品說來不及做不來,為了捍衛(wèi)開發(fā)的尊嚴(yán):)