Search code examples
iosswiftnsattributedstringnsmutableattributedstring

NSMutableAttributedString addAttribute for range apply for all string


I have created NSMutableAttributedString with different attributes and then for one range I added attribute with bold font. Example

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)
            }
        }

But when I launched application I saw all string with bold font. I saw attributed string in debug and it looked like this:

 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";
}

As I understood debug information is okay, but why in iOS simulator I see all string with bold font?


Solution

  • Please see the document of attributedText of UILabel:

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

    After setting attributedText of UILabel, you cannot change font , textColor or other style related property. Otherwise you will get what you have now. My guess is in some place there is a modification overlooked.