[iOS]改變UIAlertController的標(biāo)題、內(nèi)容的字體和顏色

在開發(fā)中,彈出框是必不可少的,通常情況下,我們只要彈出系統(tǒng)自帶的彈出框就可以。but,在某些情況下,萬惡的UI會(huì)要求你修改顯示文字的大小、顏色,雖然系統(tǒng)自帶有一種紅色字體的UIAlertAction,但是這種Action并不能放在Cancel位置,所以,更多時(shí)候,需要我們自己修改文字字體和顏色。
我采用的方法是KVC:
正常情況下,我們配置出來的UIAlertController是這樣的:

123.png

或者是這樣:

345.png

代碼如下:

    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:@"提示內(nèi)容" preferredStyle:UIAlertControllerStyleAlert];
//    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:@"提示內(nèi)容" preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction *defaultAction = [UIAlertAction actionWithTitle:@"Default" style:UIAlertActionStyleDefault handler:nil];
    UIAlertAction *destructiveAction = [UIAlertAction actionWithTitle:@"Destructive" style:UIAlertActionStyleDestructive handler:nil];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:nil];
    
    [alertController addAction:defaultAction];
    [alertController addAction:destructiveAction];
    [alertController addAction:cancelAction];
    
    [self presentViewController:alertController animated:YES completion:nil];

代碼里展示了系統(tǒng)提供的三種UIAlertAction,現(xiàn)在我們要對(duì)文字的字體和顏色進(jìn)行設(shè)置:

  • 1.標(biāo)題和提示內(nèi)容的文字設(shè)置
    代碼如下:
//修改title
    NSMutableAttributedString *alertControllerStr = [[NSMutableAttributedString alloc] initWithString:@"提示"];
    [alertControllerStr addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0, 2)];
    [alertControllerStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:17] range:NSMakeRange(0, 2)];
    [alertController setValue:alertControllerStr forKey:@"attributedTitle"];

    //修改message
    NSMutableAttributedString *alertControllerMessageStr = [[NSMutableAttributedString alloc] initWithString:@"提示內(nèi)容"];
    [alertControllerMessageStr addAttribute:NSForegroundColorAttributeName value:[UIColor greenColor] range:NSMakeRange(0, 4)];
    [alertControllerMessageStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:20] range:NSMakeRange(0, 4)];
    [alertController setValue:alertControllerMessageStr forKey:@"attributedMessage"];

效果如下:

123.png
  • 2.設(shè)置按鈕文字,就拿取消按鈕距離:
    代碼如下:
    //修改按鈕
    if (cancelAction valueForKey:@"titleTextColor") {
        [cancelAction setValue:[UIColor redColor] forKey:@"titleTextColor"];
    }

效果如下:

123.png

至于里面的key值怎么得到的,過兩天會(huì)寫一篇文章來講述。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容