Swift - 缓慢的 UITableView 滚动(从设备存储加载图像)

Swift - Slow UITableView scroll (loading image from device storage)

我有一个 UITableView 填充了包含 just 文本标签 文本标签和 UI图片。当应用程序是 运行 时,图像从我的服务器下载并存储在本地设备上。每次应用 运行,应用都会检查新图像并下载它们。在我的 cellForRowAtIndexPath 函数中,我在后台线程上从设备存储加载图像,然后在主线程上更新 UI。

我不知道我这样做是否正确,但这是我在 cellForRowAtIndexPath 函数中显示图像的代码:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
        for image in self.postsImages {
            if ((image as! NSArray)[0] as! Int == postIDCurrent) {
                // there is an image associated with this post

                let postImage = UIImage(contentsOfFile: (currentArray.lastObject as? String)!)
                dispatch_async(dispatch_get_main_queue(), {
                    cell.postImageView.image = postImage
                    cell.postImageView.clipsToBounds = true
                    cell.postImageView.userInteractionEnabled = true
                    cell.postImageView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(PostsTableViewController.imageTapped(_:))))
                })
            }
        }
    })

forif 语句都只是真正检查是否有与我们要显示的当前单元格关联的图像。

如果我没有提供足够的信息,我深表歉意。如果您还需要什么,请评论。

无论如何,我的问题是,这段代码有什么问题导致我的 UITableView 滚动速度很慢?

尝试打破你的 for 循环:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
    for image in self.postsImages {
        if ((image as! NSArray)[0] as! Int == postIDCurrent) {
            // there is an image associated with this post

            let postImage = UIImage(contentsOfFile: (currentArray.lastObject as? String)!)
            dispatch_async(dispatch_get_main_queue(), {
                cell.postImageView.image = postImage
                cell.postImageView.clipsToBounds = true
                cell.postImageView.userInteractionEnabled = true
                cell.postImageView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(PostsTableViewController.imageTapped(_:))))
            })
            break
        }
    }
})

有可能 postImage 比 cell.postImageView 的边界大得多,因此主线程上的分配需要花费大量时间来缩小它。假设 postImageView 的边界是可预见的,在后台线程中将图像缩放到正确的大小很可能会解决这个问题。如果您没有方便的调整大小功能,this gist looks reasonable.