【发布时间】:2016-04-12 10:35:51
【问题描述】:
我有一个UITableView 和很多UITableViewCell,我使用此代码将内容和图像加载到UITableCell,但每个UITableViewCell 的图像显示需要很长时间。
var loadOnce : [String] = []
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCellWithIdentifier("ProfileActivities", forIndexPath: indexPath) as! ProfileActivitiesTableViewCell
if !loadOnce.contains("\(indexPath.row)") {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
let LocationImage = self.postmap[indexPath.row]
let LocationImageUrl = NSURL(string: LocationImage)
let LocationImageData = NSData(contentsOfURL: LocationImageUrl!)
let ProfileImage = self.postimg[indexPath.row]
let ProfileImageUrl = NSURL(string: ProfileImage)
let ProfileImageData = NSData(contentsOfURL: ProfileImageUrl!)
dispatch_async(dispatch_get_main_queue(), {
cell.locationImg.image = UIImage(data: LocationImageData!)
cell.activitesProfileImg.image = UIImage(data: ProfileImageData!)
});
});
loadOnce.append("\(indexPath.row)")
}
return cell
}
将代码放在 dispatch_async 中使滚动变得窒息,但加载图像仍然需要时间。
考虑到我有很多图片,比如 Facebook 或 Instagram,如何让它更快地加载图片。
谢谢。
【问题讨论】:
-
您正在加载的图像的尺寸是多少?如果您只是显示缩略图,请确保下载具有小分辨率而不是高分辨率图像的图像的缩略图版本。但最后,对于图像源的缓慢互联网连接,您无能为力。如果您可以自己将它们缓存在 CDN 上,这会有所帮助。
-
你的代码也不会像这样工作,因为你没有在任何地方缓存你的图像。因此,当来回滚动时,由于您的 loadOnce 数组,图像不会被第二次加载,但它们也不会从您的缓存中获取(并且出队的单元格将保留以前存在的图像,这可能是错误的行)。
-
像 SeanLintern88 所说的那样使用 SDWebImage。这十分完美。我也在用它
-
@dirkgroten 为什么我需要第二次加载图像,对不起,但我是 swift 的新手,我需要知道为什么,我也尝试使用 SDWebImage 捕获 n 查看结果,顺便说一句,我只使用 1 个图像进行测试@ 987654321@
-
@DavidSeek 是的,我会试试看 :)
标签: ios swift uitableview uiimage