Cen92
Cen92

Reputation: 171

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

I have a table view, in which the cells have a label with some attributed text. The text is being set correctly from cellForRowAtIndexPath. The color of the text is being correctly set but the bold attribute is not being displayed until the cell is dequeued.

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
        MyCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellIdentifier];
        Model *model = [self.fetchedResultsController objectAtIndexPath:indexPath];
        cell.tag = indexPath.row;
        [cell updateContentWithModel:model atIndexPath:indexPath];
        return cell;
}


- (void)updateContentWithModel:(Model *)model atIndexPath:(NSIndexPath *)indexPath
{
self.model = model;
[self setTextFromModel];
[self setImageFromModelAtIndexPath:indexPath];
}

- (void) setTextFromModel
{
self.title.text = self.model.header;
self.status.attributedText = [self boldString:self.model.status fontSize:self.status.font.pointSize color:[UIColor redColor]];
}

+(NSMutableAttributedString *)boldString:(NSString *)stringToBold fontSize:(CGFloat)fontSize color:(UIColor *)color
{
NSMutableAttributedString *boldString = [[NSMutableAttributedString alloc] initWithString:stringToBold];
[boldString setAttributes:@{NSForegroundColorAttributeName: color,
                            NSFontAttributeName:[UIFont boldSystemFontOfSize:fontSize]} range:NSMakeRange(0, boldString.length)];
return boldString;
}

Has anyone experience something like this before?

Upvotes: 6

Views: 3195

Answers (3)

sabius
sabius

Reputation: 784

For me, the issue was that I was using custom subclass of UILabel, which was using UIAppearance for colors. When I switched to using regular UILabel the issue got resolved, but now I had to handle font color myself, instead of using UIAppearance

Upvotes: 1

T'Pol
T'Pol

Reputation: 339

I had a similar problem. I was trying to set attributed text (specifically font color) on a UILabel in my custom UITableViewCell and it was only partially reflecting the change, even if I did it in tableView:willDisplayCell:forRowAtIndexPath: (which I believe is the recommended place to do such updates).

It turned out that I needed to set the property on the main thread:

dispatch_async(dispatch_get_main_queue(), ^{
            [label setAttributedText:text];
        });

While I was already aware that all UI updates are to be done on the main thread, I was frankly surprised that willDisplayCell wasn't already called from the main thread, at least not in this case.

Upvotes: 4

Petrovichev Maxim
Petrovichev Maxim

Reputation: 69

I have same problem due to UIAppearance. Set font\color to nil before setting UILabel attributed text works for me.

Upvotes: 6

Related Questions