简体   繁体   English

使可重用的UITableViewCell出队时,属性字符串字体格式会更改

[英]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 . 我有一个UITableView ,其中包含要在UILabel上设置NSAttributedString单元格。 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. NSAttributedString具有使用<b>%@</b> by <b>%@</b>加粗的HTML部分,它们在第一次通过时正确呈现,但是当再次调用单元格时,整个字符串都以粗体显示,而不是各个部分。

I prepare the NSAttributedString with this function. 我用此函数准备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;
}

A couple ways to solve this: 解决此问题的几种方法:

1) 1)

In your custom UITableViewCell, you should implement prepareForReuse : 在自定义UITableViewCell中,应该实现prepareForReuse

-(void)prepareForReuse{
    [super prepareForReuse];

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

2) 2)

After you dequeue your table view cell in your cellForRowAtIndexPath method, you can do something like: cellForRowAtIndexPath方法中使表格视图单元出队后,可以执行以下操作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM