You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 16:24:02