显示来自 URL 的图像的 UITableView 出现断断续续的滚动

Choppy scroll on UITableView displaying images from URL

我的 table 视图在滚动时出现断断续续的问题,因为它在 cellForItemAtIndexPath 的函数中加载了每个图像 我已经搜索了一些示例,这些是我已经找到的东西试过了还是有同样的问题。

所以我有这个

var arrRes = [[String:AnyObject]]()

然后内部视图确实加载了我发出了一个 Alamofire GET 请求并使用 swiftyJSON 我将 json 文件存储到上面的字典中。

if let resData = swiftyJsonVar["events"].arrayObject {
  self.arrRes = resData as! [[String:AnyObject]]
}
self.tableview2.reloadData()




func numberOfSectionsInTableView(tableView: UITableView) -> Int {

    return 1

}


func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    return arrRes.count
}



func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCellWithIdentifier("mapCell", forIndexPath: indexPath) as! locationEventsTableViewCell

    var dict = arrRes[indexPath.row]

    cell.eventTitle.text = dict["eventName"] as? String

    let cal = dict["eventStarttime"] as? String



    let dateF = NSDateFormatter()
    dateF.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
    let date:NSDate = dateF.dateFromString(cal!)!


    let d = NSDateFormatter()

    d.dateFormat = "dd-MM-yyyy HH:mm"
    let d1 = d.stringFromDate(date)
    cell.eventDate.text = d1
    let at = dict["eventStats"]?["attendingCount"] as? Int
    let kapa = at?.stringValue
    cell.eventAttends.text = kapa
    let imageDef : UIImage = UIImage(named: "noimage")!


    let priority = DISPATCH_QUEUE_PRIORITY_DEFAULT
    dispatch_async(dispatch_get_global_queue(priority, 0)) {
    if let theImage = dict["eventCoverPicture"] as? String {

        let url = NSURL(string: theImage)

        if url != nil {
            let data = NSData(contentsOfURL: url!)
            dispatch_async(dispatch_get_main_queue()) {
            cell.eventImage.image = UIImage(data: data!)

            }

        } else {
            cell.eventImage.image = imageDef
        }


    }
    }



    return cell

}

正如你所看到的,我正在使用分派异步函数来获取图像,即使我有或没有它仍然不稳定。

有没有人对此有任何解决方案?谢谢!

所以问题在于,每次显示 UITableView 时,您都从 URL 调用图像。每次单元格离开屏幕并返回时,它都会调用从服务器检索图像的方法。

在 UI 尝试执行时正在执行服务器调用,这包括滚动和其他视觉负载。

根据应用程序,您可以在加载 tableView 并将它们存储在本地之前下载 UITableView 的所有图像。我还会研究 NSCache,因为这可能更适合您的应用。

目标是 UI 永远是第一要务。因此,如果 UITableView 中有一些东西需要像您的 eventCoverPicture 一样,请在加载 UITableView 之前加载它们或从内存中调用它们。

  1. 这可确保您进行最少数量的服务器调用以减少用户网络负载。

  2. UI 被打断,您的用户可以滚动浏览他们的应用程序而不会出现这种断断续续的情况。

我认为您的代码关于异步 api 是正确的。可能是 NSDateFormatter 拖慢了你的速度。日期格式化程序很重 API。使用记忆,它也会提高性能。

class MyObject {

    // define static variable

    private static let formatter: NSDateFormatter = {
        let formatter = NSDateFormatter()
        formatter.dateFormat = "EEE MMM dd HH:mm:ss Z yyyy"
        return formatter
    }()

    // you could use it like so

    func someMethod(date: NSDate) -> String {

        return MyObject.formatter.stringFromDate(date)
    }
}