com.iavian com.iavian - 1 month ago 10
iOS Question

Load Image async for NSTextAttachment for UITableViewCell

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))
}

Answer

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

Comments