范围的NSMutableAttributedString addAttribute适用于所有字符串

时间:2019-02-11 10:42:49

标签: ios swift nsattributedstring nsmutableattributedstring

我创建了具有不同属性的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模拟器中我看到所有带有粗体字体的字符串?

1 个答案:

答案 0 :(得分:0)

请参阅UILabel的attributedText文档:

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

设置了UILabel的attributedText之后,您将无法更改font,textColor或其他与样式相关的属性。否则,您将获得现在拥有的东西。 我的猜测是某个地方忽略了修改。

相关问题