NSMutableAttributedString addAttribute for range 适用于所有字符串

NSMutableAttributedString addAttribute for range apply for all string

我创建了具有不同属性的 NSMutableAttributedString,然后为一个范围添加了粗体字体的属性。例子

let attText = NSMutableAttributedString(string: string, attributes: [
            NSAttributedString.Key.font: UIFont.systemFont(ofSize: 15),
            NSAttributedString.Key.foregroundColor: UIColor.Branding.darkText,
            NSAttributedString.Key.paragraphStyle: paragraphStyle
        ])
        if let word = string.components(separatedBy: " ").first {
            let range = attText.mutableString.range(of: word, options: .caseInsensitive)
            if range.location != NSNotFound {
                attText.addAttribute(NSAttributedString.Key.font, value: UIFont.systemFont(ofSize: 15, weight: .semibold), range: range)
            }
        }

但是当我启动应用程序时,我看到所有字符串都是粗体。我在调试中看到了属性字符串,它看起来像这样:

 some : Create{
    NSColor = "UIExtendedSRGBColorSpace 0.247059 0.278431 0.337255 1";
    NSFont = "<UICTFont: 0x7ff1c1c169e0> font-family: \".SFUIText-Semibold\"; font-weight: bold; font-style: normal; font-size: 15.00pt";
}
tasks for people{
    NSColor = "UIExtendedSRGBColorSpace 0.247059 0.278431 0.337255 1";
    NSFont = "<UICTFont: 0x7ff1c1c388d0> font-family: \".SFUIText\"; font-weight: normal; font-style: normal; font-size: 15.00pt";
}

据我所知,调试信息是可以的,但为什么在 iOS 模拟器中我看到所有字符串都是粗体?

请查看UILabel的attributedText文档:

  label.attributedText =  attText
  ``label.font = UIFont.systemFont(ofSize: 15, weight: .semibold)
  print(label.attributedText) 

设置UILabel的attributedText后,无法更改font、textColor或其他样式相关属性。否则你将得到你现在所拥有的。 我的猜测是在某些地方有一个修改被忽略了。