Search code examples
iosswiftnsattributedstring

Change UILabel attributed String


I use this code to add attributed strings to a label:

let attrString = NSMutableAttributedString(string: text)
// add some attributes
myLabel.attributedText = attrString

Now is it possible to change only the text of the attributed string myLabel and keeping the attributes?


Solution

  • Through it's mutableString property

    Example:

    let astrMessage = NSMutableAttributedString(string: "Hello World")
    
    //set some attributes
    astrMessage.addAttribute(NSAttributedStringKey.foregroundColor,
                             value: UIColor.blue,
                             range: NSRange(location: 0, length: 5))
    astrMessage.addAttribute(NSAttributedStringKey.foregroundColor,
                             value: UIColor.red,
                             range: NSRange(location: 6, length: 5))
    
    //update
    astrMessage.mutableString.setString("World Welcome")
    

    NOTE: Only the first attribute will be applied to the updated text.