我有一个包含多种单元格的表格视图。其中之一是带有TextView的单元格,在此文本视图中,我必须从数据渲染NSAttributedString
。这必须根据Apple documentation在主线程上完成:
不应从后台线程中调用HTML导入器(也就是说,选项字典包括NSDocumentTypeDocumentAttribute,其值为NSHTMLTextDocumentType)。它将尝试与主线程同步,失败并超时。从主线程调用它是可行的(但如果HTML包含对外部资源的引用,仍可能会超时,应不惜一切代价避免这样做)。 HTML导入机制用于实现诸如markdown之类的东西(即,文本样式,颜色等),而不是用于常规HTML导入。
但是以这种方式进行渲染将使表格视图的滚动滞后,并且会干扰自动布局。这是我的单元格内的代码。
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;
});
我像这样滚动我的tableView:
-(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];
}
}
还有其他方法可以创建属性字符串而不会出现这些问题吗?
我认为您必须在您的Model类中创建属性字符串,以便该行方法的表视图单元格在滚动时不会创建新的属性字符串,希望它可以帮助您,谢谢
+(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;
}
在表视图的CellforRow方法中使用此模型值