本文介绍了为UITableViewCell的NSTextAttachment加载图像异步的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在异步线程或图像缓存库(例如SDwebimage)中动态加载图像.下面的代码是我尝试过的,从网络获取图像后,它不会重新绘制.
Loading images dynamically in async thread or image cache library like SDwebimage. Below code is what I tried and it doesn't repaint after image fetched from network.
let mutableAttributedString = NSMutableAttributedString()
if let _img = newsItem.img {
var attachment = NSTextAttachment()
attachment.bounds = CGRectMake(4, 4, expectedWidth, expectedWidth * _img.ratio)
dispatch_async(dispatch_get_main_queue(), { () -> Void in
attachment.image = UIImage(data: NSData(contentsOfURL: NSURL(string: _img.src)!)!)
})
mutableAttributedString.appendAttributedString(NSAttributedString(attachment: attachment))
}
推荐答案
设置NSTextAttachment
的image
后,您需要强制刷新textView
内容.为此,您可以使用textView.layoutManager's
方法invalidateDisplayCharacterRange
,其中range
-是NSTextAttachement子字符串的范围
After image
of NSTextAttachment
was set, you need to force refreshing of textView
contents. For that you can use textView.layoutManager's
method invalidateDisplayCharacterRange
, where range
- is the range of your NSTextAttachement substring
这篇关于为UITableViewCell的NSTextAttachment加载图像异步的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!