Search code examples
iosobjective-cuitableviewnsattributedstring

Attributed string font formatting changes when dequeuing reusable UITableViewCell


I have a UITableView that contains cells where I'm setting an NSAttributedString on a UILabel. The NSAttributedString has sections that are HTML bolded using <b>%@</b> by <b>%@</b>, and they render correctly on the first pass however when the cell is called again the entire string is in bold, rather than the individual sections.

I prepare the NSAttributedString with this function.

- (NSAttributedString *)attributedStringForString:(NSString *)string forFont:(UIFont *)font {
    NSLog(@"Get attributed string");
    string = [string stringByAppendingString:[NSString stringWithFormat:@"<style>body{font-family: '%@'; font-size:%fpx; color:#000000;}</style>",
                                              font.fontName,
                                              font.pointSize]];

    NSDictionary *options = @{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType};
    NSAttributedString *labelString = [[NSAttributedString alloc] initWithData:[string dataUsingEncoding:NSUTF8StringEncoding] options:options documentAttributes:nil error:nil];

    return labelString;
}

Solution

  • A couple ways to solve this:

    1)

    In your custom UITableViewCell, you should implement prepareForReuse:

    -(void)prepareForReuse{
        [super prepareForReuse];
    
        // Then Reset here back to default values that you want.
        self.label.font = [UIFont systemFontOfSize: 12.0f];
    }
    

    2)

    After you dequeue your table view cell in your cellForRowAtIndexPath method, you can do something like:

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if(cell)
    {
        cell.textLabel.font = [UIFont systemFontOfSize: 12.0f];
    }