Kiril Savino
Kiril Savino

Reputation: 79

UILabel with attributedText in custom UITableViewCell: Color not rendering until reuse (iOS10)

I have a convenience extension like this:

extension NSMutableAttributedString {

    func append(string: String, attributes: [String: Any]) {
        let attributed = NSMutableAttributedString(string: string)
        let range = NSRange(location: 0, length: string.utf16.count)
        for (attribute, value) in attributes {
            attributed.addAttribute(attribute, value: value, range: range)
        }
        append(attributed)
    }
}

I'm styling text in my UILabel thusly:

let normalAttributes = [NSForegroundColorAttributeName: darkGray]
let lightAttributes = [NSForegroundColorAttributeName: lightGray]
let text = NSMutableAttributableString()
text.append("Part 1", attributes: normalAttributes)
text.append("Part 2", attributes: lightAttributes)

All of this within a custom UITableViewCell class. What's happening is that the text is rendering with the base color in the NIB file, rather than the custom foreground color as per my attributed string - until I do something (like scroll around) that causes cell reuse, after which suddenly the colors render correctly.

I can't seem to find anything wrong with the lifecycle of the object, and there's no other place that's messing with this label. The label, fwiw, is an IBOutlet, so I'm not creating a new one each time or anything strange.

Upvotes: 1

Views: 2505

Answers (2)

Rashesh Bosamiya
Rashesh Bosamiya

Reputation: 629

As @Kiril Savino suggested. Setting up Font & Color of UILabel to nil is do easy work-around to get it done.

But one more thing I noticed today is Default Font used from Storyboard or XIB.

It should be System Font from Storyboard or XIB to make this work. If you have used other Custom Font, then it won't work.

So, make sure Default Font of UILabel should System Font.

Thank you.

Upvotes: 0

Kiril Savino
Kiril Savino

Reputation: 79

Turns out it's the same problem as:

Attributed string in tableviewcell not showing bold text until the cell is dequeued and reloaded

So it's solved by setting the font & color to nil on the label before setting the attributeText. Annoying, but easy enough to do that work-around.

Upvotes: 5

Related Questions