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

iOS开发中NSAttributedString下划线样式不生效问题求助

解决UILabel下划线不显示的问题

嘿,我来帮你搞定这个下划线不显示的问题~结合你的代码和环境,我整理了几个可能的原因和对应的解决方案:

1. 下划线样式参数类型错误

你代码里直接传了NSUnderlineStyle.single给underlineStyle属性,但实际上这个属性需要的是Int类型的原始值,而不是枚举本身。NSUnderlineStyle是OptionSet类型,需要通过.rawValue来获取它的整数表示,不然系统无法正确解析样式。

修正后的代码:

let attributedString = NSMutableAttributedString(string: "Hello World!")
// 这里要使用rawValue获取枚举对应的整数值
attributedString.addAttribute(NSAttributedString.Key.underlineStyle, 
                              value: NSUnderlineStyle.single.rawValue, 
                              range: NSRange(location: 0, length: attributedString.length))
label.attributedText = attributedString

2. 检查是否覆盖了attributedText

确认你的代码里有没有在设置attributedText之后,又给label.text赋值了?如果有的话,text属性会覆盖attributedText,导致下划线样式丢失。

比如下面这种错误写法要避免:

label.attributedText = attributedString
label.text = "Hello World!" // 这行会覆盖之前的富文本样式

3. 模拟器渲染缓存问题(小概率)

如果上面的方法都试过还是不行,可以试试:

  • 重启iOS模拟器
  • 清理Xcode缓存(Cmd+Shift+K)
  • 重新编译运行项目

这些操作可以解决偶尔出现的模拟器渲染异常问题。

内容的提问来源于stack exchange,提问作者Charlie Fish

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 23:17:31