[英]Swift - Slow UITableView scroll (loading image from device storage)
我有一个UITableView,其中填充了仅包含文本标签或文本标签和UIImage的单元格。 运行该应用程序时,图像将从我的服务器下载并本地存储在设备上。 每次运行该应用程序时,该应用程序都会检查并下载新图像。 在我的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(_:))))
})
}
}
})
for
和if
语句实际上只是检查是否有与我们要显示的当前单元格关联的图像。
很抱歉,如果我没有提供足够的信息。 如果您还有其他需要,请发表评论。
无论如何,我的问题是,此代码导致UITableView滚动速度非常慢,我在做什么问题?
很有可能postImage比cell.postImageView的边界大得多,因此在主线程上进行分配会花费大量时间来缩小它。 假设postImageView的边界是可预见的,那么在后台线程中将图像缩放到正确的大小很有可能会解决这个问题。 如果您没有方便的调整大小功能,那么这个要点看起来很合理 。
尝试中断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
}
}
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.