【问题标题】:NSMutableAttributedString addAttribute for range apply for all stringNSMutableAttributedString addAttribute for range 适用于所有字符串
【发布时间】:2019-02-11 10:42:49
【问题描述】:

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

【问题讨论】:

  • 你在哪里设置myLabelOrTextView.attributedText = attText
  • 我没有留下设置属性文本的代码,但在调试信息中你可以看到我标签的属性文本。所以它设置正确。
  • 你是否在某个时间点设置label.font
  • 仅在界面生成器中。而且这个字体是Regular而不是粗体

标签: ios swift nsattributedstring nsmutableattributedstring


【解决方案1】:

请看UILabelattributedText的文档:

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

设置 UILabel 的属性文本后,不能更改字体、文本颜色或其他样式相关属性。否则你会得到你现在所拥有的。 我的猜测是在某些地方忽略了修改。

【讨论】:

  • 但是我在设置属性文本后并没有改变字体、文本颜色等
  • 你可能会改变一些你不知道的地方。但这是我可以重复这个问题的唯一原因,您可以将 VC 提取到一个新项目中并进行尝试。
  • 是的,真的,我添加了观察者并找到了在我的设置之后设置属性字符串的代码。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-10-25
  • 1970-01-01
  • 2017-01-06
  • 1970-01-01
  • 2014-07-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多