Search code examples
iosswiftswift3uilabelnsmutableattributedstring

NSMutableAttributedString not working in ViewController but works in Playground


I have a problem with this code and I do not know what I am doing wrong. I tried everything in Playground first and it works like a charm. Assigning this to the UILabel it just not working.

let nameSurname = "\(postAddSetup.nameSurname.text!)"
let checkIn = " - \(setLocationPlace), \(setLocationCity)"

var string = postAddSetup.nameSurname.text
string = "\(nameSurname) \(checkIn)"

let boldUsername = NSMutableAttributedString(string: string!)
boldUsername.addAttribute(NSFontAttributeName, value: UIFont.boldSystemFont(ofSize: 14), range: (string! as NSString).range(of: nameSurname))
let normalCheckIn = NSMutableAttributedString(string: string!)
normalCheckIn.addAttribute(NSFontAttributeName, value: UIFont.systemFont(ofSize: 11), range: (string! as NSString).range(of: checkIn))
normalCheckIn.addAttribute(NSForegroundColorAttributeName, value: UIColor.darkGray, range: (string! as NSString).range(of: checkIn))
print(string!)

postAddSetup.nameSurname.text = string!

I practically have a label that is getting a text from 2 strings. Those strings I want to be displayed with different colors and fonts. It works in Playground but not in the ViewController. Can anybody help, please?


Solution

  • In your example you have two different attributed string created from the same original string and you are passing your string without attributes to the label text property. Instead you can create a unique attributed string and you can use it with attributedText property of your label:

    var string = postAddSetup.nameSurname.text
        string = "\(nameSurname) \(checkIn)"
    
        let attributedString = NSMutableAttributedString(string: string!)
        attributedString.addAttribute(NSFontAttributeName, value: UIFont.boldSystemFont(ofSize: 14), range: (string! as NSString).range(of: nameSurname))
        attributedString.addAttribute(NSFontAttributeName, value: UIFont.systemFont(ofSize: 11), range: (string! as NSString).range(of: checkIn))
        attributedString.addAttribute(NSForegroundColorAttributeName, value: UIColor.darkGray, range: (string! as NSString).range(of: checkIn))
    
        postAddSetup.nameSurname.attributedText = attributedString