带有 NSAttributedString 的单元格使 UITableView 的滚动变慢

Cell with NSAttributedString makes the scrolling of UITableView slow

我有一个包含多种单元格的 table 视图。其中之一是带有 TextView 的单元格,在此文本视图中,我必须从数据中呈现 NSAttributedString。这必须根据 Apple documentation:

在主线程上完成

The HTML importer should not be called from a background thread (that is, the options dictionary includes NSDocumentTypeDocumentAttribute with a value of NSHTMLTextDocumentType). It will try to synchronize with the main thread, fail, and time out. Calling it from the main thread works (but can still time out if the HTML contains references to external resources, which should be avoided at all costs). The HTML import mechanism is meant for implementing something like markdown (that is, text styles, colors, and so on), not for general HTML import.

但是以这种方式呈现会导致 table 视图的滚动滞后,并且还会扰乱自动布局。这是我的单元格中的代码。

dispatch_async(dispatch_get_main_queue(), ^{
    NSString* htmlString = [NSString stringWithFormat:@"<div style=\"font-family:%@; font-size:%dpx; color:#08080d;\">%@</div>",fontNameBase, 16,txt];
    htmlString = [Utility replaceHtmlCodeEntities:htmlString];
    NSData* tempData = [htmlString dataUsingEncoding:NSUnicodeStringEncoding];
    NSAttributedString *attributedString = [[NSAttributedString alloc] initWithData:tempData  options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType} documentAttributes:nil error:nil];
    self.textViewMsg.attributedText = txt;
});

我滚动我的table视图是这样的:

-(void)reloadAndScroll{
    [self.tableChat reloadData];

    long lastRowNumber = [_tableChat numberOfRowsInSection:0] - 1;
    if (lastRowNumber > 0) {
        NSIndexPath* indexPath = [NSIndexPath indexPathForRow:lastRowNumber inSection:0];
        [_tableChat scrollToRowAtIndexPath:indexPath        
        atScrollPosition:UITableViewScrollPositionBottom animated:NO];
    }
}

有没有其他方法可以创建没有这些问题的属性字符串?

我认为你必须在你的模型中创建属性字符串 class,这样 table 行方法的视图单元格不会在滚动时创建新的属性字符串,希望它对你有帮助出去,谢谢

+(AttributedModel *)methodToGetAttributedDetail :(NSString *)txt {

    AttributedModel *objModel = [[AttributedModel alloc] init];

   NSString* htmlString = [NSString stringWithFormat:@"<div style=\"font-family:%@; font-size:%dpx; color:#08080d;\">%@</div>",fontNameBase, 16,txt];
   htmlString = [Utility replaceHtmlCodeEntities:htmlString];
   NSData* tempData = [htmlString dataUsingEncoding:NSUnicodeStringEncoding];
   NSAttributedString *attributedString = [[NSAttributedString alloc] initWithData:tempData  options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType} documentAttributes:nil error:nil];

   objModel.attributedString  = attributedString;

   return objModel;
}

在 table 视图的 CellforRow 方法中使用此模型值