NSAttributedString分段设置下划线颜色在UILabel未正确生效如何解决?
问题原因
该问题由UILabel的富文本下划线默认渲染机制导致:系统会自动合并相邻、下划线样式相同(仅校验underlineStyle字段,不区分下划线颜色)的下划线为一条连续线段,统一使用合并区间起始位置的下划线颜色,因此你设置的分段下划线颜色不会生效。
解决方案
方案1:插入零宽分隔符(最简单,侵入性低)
在不同样式的文本段之间插入零宽度空格\u{200B},并给零宽空格设置无下划线属性,强制打断系统的连续下划线合并逻辑。零宽空格不会改变文本视觉宽度,也不会被用户感知。
// 构建带零宽分隔符的字符串,打断连续下划线渲染 let fullString = "A\u{200B}B\u{200B}C" let attributedTitle = NSMutableAttributedString(string: fullString) // 给字符A设置样式 attributedTitle.addAttributes([ .foregroundColor: UIColor.black, .underlineColor: UIColor.black, .underlineStyle: NSUnderlineStyle.single.rawValue ], range: NSRange(location: 0, length: 1)) // 给第一个零宽空格设置无下划线属性 attributedTitle.addAttributes([ .underlineStyle: 0 ], range: NSRange(location: 1, length: 1)) // 给字符B设置样式 attributedTitle.addAttributes([ .foregroundColor: UIColor.yellow, .underlineColor: UIColor.yellow, .underlineStyle: NSUnderlineStyle.single.rawValue ], range: NSRange(location: 2, length: 1)) // 给第二个零宽空格设置无下划线属性 attributedTitle.addAttributes([ .underlineStyle: 0 ], range: NSRange(location: 3, length: 1)) // 给字符C设置样式 attributedTitle.addAttributes([ .foregroundColor: UIColor.black, .underlineColor: UIColor.black, .underlineStyle: NSUnderlineStyle.single.rawValue ], range: NSRange(location: 4, length: 1)) let label = UILabel() label.attributedText = attributedTitle
方案2:自定义UILabel绘制(适合复杂场景)
如果不想修改原始文本内容,可以重写UILabel的draw(_ rect: CGRect)方法,遍历富文本的所有属性分段,根据每一段的frame和下划线属性手动绘制对应颜色的下划线,灵活性更高。
内容的提问来源于stack exchange,提问作者Kei Ishida
相关产品推荐
相关产品推荐

