Collin Bell
Collin Bell

Reputation: 384

Swift: NSMutableAttributedString foregroundColor not setting properly

I need the first character of my UILabel to be a different color than the rest of the label. I'm using the following code:

        let attributedString: NSMutableAttributedString = NSMutableAttributedString(string: cell.label.text!)
        attributedString.addAttribute(NSAttributedStringKey.foregroundColor, value: UIColor.red, range: NSRange(location: 0, length: 1))
        cell.label.attributedText = attributedString

This is just causing the first character to vanish. A print statement for attributedString looks like this (apparently correct):

■{NSForegroundColor = "UIExtendedSRGBColorSpace 1 0 0 1";} restOfText{}

What am I doing wrong?

Upvotes: 0

Views: 282

Answers (2)

vadian
vadian

Reputation: 285069

The problem is the NSRange value with length 1. For Swift strings use the dedicated NSRange initializer taking the String.Index range and the target string

let string = cell.label.text!
let attributedString: NSMutableAttributedString = NSMutableAttributedString(string: string)
attributedString.addAttribute(NSAttributedStringKey.foregroundColor, value: UIColor.red, range: NSRange(...string.startIndex, in: string ))

Upvotes: 1

Collin Bell
Collin Bell

Reputation: 384

The code as written works no problem. I accidentally overwrote cell.label.text later. Whoops

Upvotes: 0

Related Questions