UIAlertController設定自定義的標題和內容
阿新 • • 發佈:2019-01-10
我們知道,UIAlertController
的標題和內容都是黑色的,但是在很多場景下都需要修改他們的顏色,比如在輸入錯誤時把提示資訊變為紅色,或者自定義標題的顏色,可是在公開的API介面中好像並沒有對應的方法,那麼我們應該怎麼做呢?
第三方控制元件
第一種方法當然就是使用第三方的Alert
控制元件了,現在Github上有著眾多的Alert
控制元件(如SCLAlertView
等),相信有很多都可以滿足大家的需求,只要使用Cocoapods新增新增第三方庫就可以了。KVC方法
但是也有一些人,不願意去使用第三方庫,而是想要使用系統的UIAlertController
,這樣當然也是可以的。蘋果公司並沒有完全的封死對UIAlertController
NSAttributedString
把字型和顏色設定好,然後在通過KVC的方法進行設定,就可以了。下面是一個示例程式碼和對應的截圖:
- (void)testAlert { UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleAlert]; [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]]; NSDictionary *titleAttr = @{ NSFontAttributeName:[UIFont boldSystemFontOfSize:20], NSForegroundColorAttributeName:[UIColor greenColor] }; NSAttributedString *attributedTitle = [[NSAttributedString alloc] initWithString:@"測試有顏色標題" attributes:titleAttr]; [alert setValue:attributedTitle forKey:@"attributedTitle"]; NSDictionary *messageAttr = @{ NSFontAttributeName:[UIFont systemFontOfSize:12], NSForegroundColorAttributeName:[UIColor redColor] }; NSAttributedString *attributedMessage = [[NSAttributedString alloc] initWithString:@"測試有顏色文字" attributes:messageAttr]; [alert setValue:attributedMessage forKey:@"attributedMessage"]; [self presentViewController:alert animated:YES completion:nil]; }
關於自定義標題和內容就說這麼些了,主要還是要看程式碼才能明白。