首先我們看一下修改後的效果:
具體的方法如下:
NSString *message = @"請確認信息是否正確?";
NSString *title = @"提示";
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleActionSheet];
//改變title的大小和顏色
NSMutableAttributedString *titleAtt = [[NSMutableAttributedString alloc] initWithString:title];
[titleAtt addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:16] range:NSMakeRange(0, title.length)];
[titleAtt addAttribute:NSForegroundColorAttributeName value:[UIColor orangeColor] range:NSMakeRange(0, title.length)];
[alertController setValue:titleAtt forKey:@"attributedTitle"];
//改變message的大小和顏色
NSMutableAttributedString *messageAtt = [[NSMutableAttributedString alloc] initWithString:message];
[messageAtt addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:13] range:NSMakeRange(0, message.length)];
[messageAtt addAttribute:NSForegroundColorAttributeName value:[UIColor yellowColor] range:NSMakeRange(0, message.length)];
[alertController setValue:messageAtt forKey:@"attributedMessage"];
[self presentViewController:alertController animated:YES completion:nil];
上面的是修改UIAlertViewController的title和message字體的大小和顏色,採用的是修改attributedString其中的NSForegroundColorAttributeName顏色屬性和NSFontAttributeName字體大小屬性。UIAlertViewController中的標題的key:@"attributedTitle",標題中提示信息的key:@"attributedMessage"。
UIAlertAction *alertAction = [UIAlertAction actionWithTitle:@"知道了" style:UIAlertActionStyleDefault handler:nil];
[alertAction setValue:[UIColor purpleColor] forKey:@"_titleTextColor"];
// alertController.view.tintColor = [UIColor greenColor];
[alertController addAction:alertAction];
UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
/*取消按鈕的顏色*/
[cancel setValue:[UIColor redColor] forKey:@"_titleTextColor"];
[alertController addAction:cancel];
修改UIAlertViewController中修改所有按鈕的顏色使用下面這個方法:
alertController.view.tintColor = [UIColor greenColor];
修改單個UIAlertAction按鈕的字體顏色使用下面這個方法:
[cancel setValue:[UIColor redColor] forKey:@"_titleTextColor"];
有人可能會問,你怎麼知道Alertaction中有"_titleTextColor"這個key呢?其實很簡單,我們可以通過runtime獲取這個類中所有的屬性,代碼如下
unsigned int count;
Ivar *ivars = class_copyIvarList([UIAlertAction class], &count);
for (int i = 0; i < count; i++) {
Ivar ivar = ivars[i];
const char * cName = ivar_getName(ivar);
NSString *ocName = [NSString stringWithUTF8String:cName];
MYLog(@"這裏是runtime獲取到alertaction的屬性 %@",ocName);
}
free(ivars);
打印的日誌如下
會點英語的老鐵們應該知道每個單詞對應的屬性大概是幹什麼事情的吧,我們在這裏只修改顏色,所以重用到了"_titleTextColor"這個key。
如果這個能解決您的問題,請給個👍,謝謝!我還有個需求,改變這個字體大小的方法,我沒找到,如果有知道的大神,請不吝賜教!