如何为UIAlertController消息中的第二句设置不同颜色?
给UIAlertController消息中的特定句子设置不同颜色的实现方法
嘿,这个需求我碰到过好多次啦!默认的UIAlertController确实没办法直接给message里的某句话单独改颜色——因为它默认只认普通的纯文本NSString。不过别慌,用富文本NSAttributedString就能轻松搞定!
下面是具体的实现步骤和完整代码:
核心思路
我们不直接给UIAlertController传普通的message字符串,而是先构建一段带有颜色属性的富文本,然后赋值给alert的attributedMessage属性(这个属性从iOS 10开始支持,现在绝大多数APP都兼容这个版本啦)。
完整代码示例
// 1. 先把消息拆分成三段,方便单独处理第二段 NSString *firstSentence = @"This is the first sentence.\r\n\n"; NSString *secondSentence = @"This is the second sentence I want a different color.\r\n\n"; NSString *thirdSentence = @"This is the third sentence."; // 2. 创建可变富文本,先加入第一段普通文本 NSMutableAttributedString *attributedMessage = [[NSMutableAttributedString alloc] initWithString:firstSentence]; // 给第二段文本添加颜色属性(这里用红色举例,你可以换成任何UIColor) NSAttributedString *coloredSecondPart = [[NSAttributedString alloc] initWithString:secondSentence attributes:@{ NSForegroundColorAttributeName: [UIColor redColor] // 要是还想改字体,比如加粗,就加这句: // NSFontAttributeName: [UIFont boldSystemFontOfSize:16] }]; [attributedMessage appendAttributedString:coloredSecondPart]; // 加入第三段普通文本 [attributedMessage appendAttributedString:[[NSAttributedString alloc] initWithString:thirdSentence]]; // 3. 创建UIAlertController,注意这里message传nil UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Warning!!!" message:nil preferredStyle:UIAlertControllerStyleAlert]; // 给alert设置富文本消息 alert.attributedMessage = attributedMessage; // 别忘了添加确认按钮,不然弹窗没法关闭哦 UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:nil]; [alert addAction:okAction]; // 最后弹出弹窗 [self presentViewController:alert animated:YES completion:nil];
额外说明
- 除了颜色,你还可以在attributes字典里添加其他样式属性,比如字体大小、加粗、下划线等等,满足更多自定义需求。
- 如果你的APP需要兼容iOS 9及以下版本,那这个方法就不行啦,得用自定义弹窗的方案,但现在一般都不用考虑这么老的版本了。
内容的提问来源于stack exchange,提问作者LKirin
相关产品推荐
相关产品推荐

