ios - UITableView 在快速滚动期间卡住

标签 ios swift uitableview

我遇到这个问题大约 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/

相关文章:

ios - 在 iOS 中使用分割 View Controller 的问题

ios - 使用 uicollectionview Swift 更新单个 View

ios - NSFetchedResultsController 创建了太多的部分

ios - Swift Playgrounds 中的 JavaScriptCore

ios - 如何将 SwiftUI 中的 NavigationView 的标题设置为大标题(或小标题)?

swift - 在 Swift 的 Sprite 工具包中制作一个弹出窗口

iOS 和 FirebaseCrashlytics

ios - 使用自动布局 (VFL) 增加自定义单元格按钮的高度

ios - 我如何为某个文本字段创建一个函数?

ios - RACOberve subscribeNext 立即被调用