为UITableViewCell加载NSTextAttachment的图像异步

com*_*ian 2 uitableview nstextattachment ios

在异步线程或图像缓存库(如SDwebimage)中动态加载图像.下面的代码是我尝试过的,它不会在从网络获取图像后重新绘制.

    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))
    }
Run Code Online (Sandbox Code Playgroud)

Kat*_*ova 5

之后imageNSTextAttachment设置,您需要强制的清爽textView内容.为此,您可以使用textView.layoutManager's方法invalidateDisplayCharacterRange,其中range- 是您的NSTextAttachement子字符串的范围