Custom String in UILabel?

Hi Apple Dev Community,

I have a simple question regarding the usage/implementation of String within a UILabel.
So basically, I want to store and display a message in a Label. In my case, I want it to say something like:
"3 Gems Remaining!"

However, I want the "3" portion of the string to have a larger size than the rest of the string, and a different color (and possibly a different font family, too).


Is it possible to do this? Or will I have to create 2 separate Labels, one containing the number of gems remaining, and another for the rest of the message?
Thanks in advance! 🙂
KC

Accepted Reply

As suggested by Claude31, `UILabel` has a property named `attributedText`.


You can create an NSAttributedString and set it to `attributedText`, instead of setting a String to `text`.


An example:

        let attrString = NSMutableAttributedString()
        
        let numGems = 3
        let attrNumGems: [NSAttributedString.Key: Any] = [
            .font: UIFont.boldSystemFont(ofSize: 32),
            .foregroundColor: UIColor.red
        ]
        attrString.append(NSAttributedString(string: String(numGems),
                                             attributes: attrNumGems))
        let textRem = " Gems Remaining!"
        let attrTextRem: [NSAttributedString.Key: Any] = [
            .font: UIFont.systemFont(ofSize: 24),
            .foregroundColor: UIColor.black
        ]
        attrString.append(NSAttributedString(string: textRem,
                                             attributes: attrTextRem))
        
        label.attributedText = attrString

Replies

Yes, you have to use attributedString


lebel.attributedString = ....


And build the attributedString.

As suggested by Claude31, `UILabel` has a property named `attributedText`.


You can create an NSAttributedString and set it to `attributedText`, instead of setting a String to `text`.


An example:

        let attrString = NSMutableAttributedString()
        
        let numGems = 3
        let attrNumGems: [NSAttributedString.Key: Any] = [
            .font: UIFont.boldSystemFont(ofSize: 32),
            .foregroundColor: UIColor.red
        ]
        attrString.append(NSAttributedString(string: String(numGems),
                                             attributes: attrNumGems))
        let textRem = " Gems Remaining!"
        let attrTextRem: [NSAttributedString.Key: Any] = [
            .font: UIFont.systemFont(ofSize: 24),
            .foregroundColor: UIColor.black
        ]
        attrString.append(NSAttributedString(string: textRem,
                                             attributes: attrTextRem))
        
        label.attributedText = attrString