我有一个包含多种单元格的表视图。其中之一是带有 TextView 的单元格,在这个文本视图中,我必须渲染一个NSAttributedString
从数据来看。这必须在主线程上完成,根据苹果文档:
不应从后台线程调用 HTML 导入器(即选项字典包含值为 NSHTMLTextDocumentType 的 NSDocumentTypeDocumentAttribute)。它会尝试与主线程同步,失败并超时。从主线程调用它是可行的(但如果 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];
}
}
是否有其他方法可以创建属性字符串而不会出现这些问题?
我认为您必须在模型类中创建属性字符串,以便行方法的表视图单元格不会在滚动时创建新的属性字符串,希望它能很好地帮助您,谢谢
+(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 方法中使用此模型值
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)