Search code examples
iosswiftuikitnsattributedstring

Why doesn't the .foregroundColor attribute apply in an NSMutableAttributedString?


I'm trying to create an NSMutableAttributedString by setting the first part of the string a certain color and then the second part bolded. Here is what I've tried so far:

let attributedText = NSMutableAttributedString(string: String.init(format: "#%@ : ", "Field Name"),
                                               attributes: [.foregroundColor: UIColor.gray])
attributedText.append(NSMutableAttributedString(string: String.init(format: "%@", "Sample Field"),
                                         attributes: [.font: UIFont.boldSystemFont(ofSize: 16)]))
myLabel.attributedText = attributedText

What happens here is the second part is successfully bolded, but no color I apply in the first part ever gets reflected. Is there something I'm missing here?

My environment is running Swift 5 in Xcode 12.2.


Solution

  • If you want the same attributes just use a var to keep a reference to them, change the font attribute and use it when you append a new string

    let label = UILabel(frame: .init(origin: .zero, size: .init(width: 250, height: 50)))
    var attr:  [NSAttributedString.Key: Any] = [.foregroundColor: UIColor.gray]
    
    let attributedText = NSMutableAttributedString(string: .init(format: "#%@ : ", "Field Name"), attributes: attr)
    attr[.font] = UIFont.boldSystemFont(ofSize: 16)
    attributedText.append(.init(string: .init(format: "%@", "Sample Field"), attributes: attr))
    
    label.attributedText = attributedText
    label
    

    enter image description here