Swift 在带有属性字符串的UITextView中显示带有占位符的url中的图像

Swift 在带有属性字符串的UITextView中显示带有占位符的url中的图像,swift,grand-central-dispatch,ios8,Swift,Grand Central Dispatch,Ios8,我正在用swift开发用于降价的lib,它工作得很好!但有一个小问题,当我加载标记中的图像时,我放置了占位符图像并分派另一个进程来加载原始图像,如下所示: var attachment: NSTextAttachment = NSTextAttachment() attachment.image = UIImage(named: "placeholder.png") attachment.bounds = CGRect(origin: CGPoi

我正在用swift开发用于降价的lib,它工作得很好!但有一个小问题,当我加载标记中的图像时,我放置了占位符图像并分派另一个进程来加载原始图像,如下所示:

var attachment: NSTextAttachment = NSTextAttachment()

            attachment.image = UIImage(named: "placeholder.png")
            attachment.bounds = CGRect(origin: CGPointZero, size: attachment.image.size.width > UIScreen.mainScreen().bounds.width ? CGSizeMake(UIScreen.mainScreen().bounds.width, UIScreen.mainScreen().bounds.width/attachment.image.size.width * attachment.image.size.height)  : attachment.image.size )

            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { () -> Void in
                let imageData: NSData = NSData(contentsOfURL: url)

                attachment.image = UIImage(data: imageData)
                attachment.bounds = CGRect(origin: CGPointZero, size: attachment.image.size.width > UIScreen.mainScreen().bounds.width ? CGSizeMake(UIScreen.mainScreen().bounds.width, UIScreen.mainScreen().bounds.width/attachment.image.size.width * attachment.image.size.height)  : attachment.image.size )
                self.textView.setNeedsDisplay()
            })

            let attributedString: NSAttributedString = NSAttributedString(attachment: attachment)
            let lineBreak: NSAttributedString = NSAttributedString(string: "\n")

            self.markdown.deleteCharactersInRange(matchRange)

            self.markdown.insertAttributedString(attributedString, atIndex: matchRange.location)
            self.markdown.insertAttributedString(lineBreak, atIndex: matchRange.location)
但在加载图像后,直到用户开始滚动,占位符才消失,突然正确显示图像


所以我想知道问题出在哪里?

您试图从全局队列更改UI,它可能无法工作。您可能需要像这样使用主队列

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { () -> Void in
    let imageData: NSData = NSData(contentsOfURL: url)
    let image = UIImage(data: imageData)

    dispatch_async(dispatch_get_main_queue()) {
        // On the main queue (the main thread)
        attachment.image = image
        attachment.bounds = CGRect(origin: CGPointZero, size: attachment.image.size.width > UIScreen.mainScreen().bounds.width ? CGSizeMake(UIScreen.mainScreen().bounds.width, UIScreen.mainScreen().bounds.width/attachment.image.size.width * attachment.image.size.height)  : attachment.image.size )
        self.textView.setNeedsDisplay()
    }
})

这不是工作!就像以前一样,当我开始滚动占位符更改为原始图像!你有什么其他想法吗?为self.textView textStorage对象调用NSTextStorage-edited:range:changeInLength:method如何?我无法使用range,因为其他线程正在处理标记文本和查找图像链接,并删除它们并将图像插入到位,因此这将导致其他范围出错!NSTextStorage不是线程安全的。您必须知道此时将修改textstorage的哪一部分。