Search code examples
iosswiftuilabelnsattributedstring

UILabel.attributedText set attributes once and then just change text (string)


How to set UILabel text attributes only once and then just change text (string)

mTextValue.attributedText = NSAttributedString(string: "STRING", 
       attributes: 
           [NSAttributedStringKey.strokeWidth: -3.0,      
            NSAttributedStringKey.strokeColor: UIColor.black])


mTextValue.text = "NEW STRING" // won't change anything

or to set new string do I have to set NSAttributedString to .attributedText again and again?


Solution

  • You could declare a mutableAttributed string separat and change the string of it like here:

    let yourString = "my string"
    let yourAttributes = [NSAttributedStringKey.strokeWidth: -3.0, NSAttributedStringKey.strokeColor: UIColor.black] as [NSAttributedStringKey : Any]
    let mutableAttributedString = NSMutableAttributedString(string: yourString, attributes: yourAttributes)
    
    let yourNewString = "my new string"
    mutableAttributedString.mutableString.setString(yourNewString)
    

    Full example:

    import UIKit
    
    class ViewController: UIViewController {
    
        var mutableAttributedString = NSMutableAttributedString()
    
        @IBAction func buttonTapped(_ sender: Any) {
    
            mutableAttributedString.mutableString.setString("new string")
            mainLabel.attributedText = mutableAttributedString
    
        }
    
        @IBOutlet weak var mainLabel: UILabel!
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            let yourString = "my string"
            let yourAttributes = [NSAttributedStringKey.strokeWidth: -3.0, NSAttributedStringKey.strokeColor: UIColor.blue] as [NSAttributedStringKey : Any]
            mutableAttributedString = NSMutableAttributedString(string: yourString, attributes: yourAttributes)
    
            mainLabel.attributedText = mutableAttributedString
        }
    
    }