出列可重用 UITableViewCell 时属性字符串字体格式更改

Attributed string font formatting changes when dequeuing reusable UITableViewCell

我有一个 UITableView,其中包含我在 UILabel 上设置 NSAttributedString 的单元格。 NSAttributedString 的部分使用 <b>%@</b> by <b>%@</b> 加粗 HTML,并且它们在第一次传递时正确呈现,但是当再次调用单元格时,整个字符串是粗体,而不是单独的部分.

我用这个函数准备了NSAttributedString

- (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;
}

解决这个问题的几种方法:

1)

在您的自定义 UITableViewCell 中,您应该实现 prepareForReuse:

-(void)prepareForReuse{
    [super prepareForReuse];

    // Then Reset here back to default values that you want.
    self.label.font = [UIFont systemFontOfSize: 12.0f];
}

2)

cellForRowAtIndexPath 方法中将 table 视图单元格出列后,您可以执行以下操作:

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