【问题标题】:Attributed string font formatting changes when dequeuing reusable UITableViewCell出列可重用 UITableViewCell 时,属性字符串字体格式更改
【发布时间】:2025-12-19 22:20:07
【问题描述】:

我有一个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;
}

【问题讨论】:

    标签: ios objective-c uitableview nsattributedstring


    【解决方案1】:

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

    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 方法中将表格视图单元格出列后,您可以执行以下操作:

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

    【讨论】:

    • 非常感谢,由于某种原因,它会自动默认恢复为 17 号的系统字体,但这很容易解决。