我遇到这个问题大约 3-4 周。我用谷歌搜索,检查了所有内容,但仍然不起作用。请帮助我!
在每个移动滚动条上,cellForRowAtIndexPath
都会重新加载tableView
,因此,它开始卡住。
我的 cellForRowAtIndexPath
函数的表格 View 如下:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{
let cell = tableView.dequeueReusableCellWithIdentifier("cell")! as! MoviesTVC
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0),{
let dictionary = self.rows[indexPath.row] as? [String: AnyObject]
dispatch_async(dispatch_get_main_queue(),{
cell.setCell(dictionary!)
})
})
return cell
}
setCell()
函数:
func setCell(dictionary: AnyObject){
let ImgString = dictionary["src"] as? String;
let ImgUrl = NSURL(string: ImgString!);
let ImgData = NSData(contentsOfURL: ImgUrl!)
self.movImg.image = UIImage(data: ImgData!);
self.movName.text = dictionary["name"] as? String;
self.movComment.text = dictionary["caption"] as? String;
}
最佳答案
后台异步任务中有错误的代码位。目前,您仅在后台从数组中获取值,这是一个非常非常快的过程......
您应该做的是在后台运行困难的任务,然后在前台更新 UI。
let cell = tableView.dequeueReusableCellWithIdentifier("cell")! as! MoviesTVC
let dictionary = self.rows[indexPath.row] as? [String: AnyObject]
cell.setCell(dictionary!)
return cell
func setCell(dictionary: AnyObject){
let ImgString = dictionary["src"] as? String;
let ImgUrl = NSURL(string: ImgString!);
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0),{
let ImgData = NSData(contentsOfURL: ImgUrl!)
let image = UIImage(data: ImgData!);
//Possibly resize the image here in the background task
//so that the cpu doesn't need to scale it in the UI thread
dispatch_async(dispatch_get_main_queue(),{
self.movImg.image = image
})
})
self.movName.text = dictionary["name"] as? String;
self.movComment.text = dictionary["caption"] as? String;
}
编辑:回答评论中的问题。最简单的解决方案是为每个“图像”单元格添加一个属性到字典中。然后,当您加载单元格时,如果字典的“图像”属性存在,那么您可以将该图像加载到单元格中。如果它不存在,则下载它并将其保存到字典中,然后将其添加到您的单元格中。
一个更困难的解决方案是将图像下载到本地资源位置。然后使用imageNamed
从文件加载图像。这将为您处理缓存和内存释放。这将是更好的选择。
更好的是使用 CoreData。在任何这些解决方案中,当您的文件存储空间不足时,您都必须管理清理文件存储。
关于ios - UITableView 在快速滚动期间卡住,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37218463/