Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change UILabel attributed String

Tags:

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?

like image 298
J.Doe Avatar asked Aug 21 '17 13:08

J.Doe


1 Answers

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.

like image 150
staticVoidMan Avatar answered Oct 01 '22 02:10

staticVoidMan