ios - UITableView 单元格图像在滚动时不断切换单元格

标签 ios swift uitableview api uiimage

我有一个对象数组(其中包括从 Google Places API 下载照片所需的数据),当我尝试在 tableView 单元格中加载这些对象的元素时,图像和 titleLabels 不断切换滚动时左右移动。

这是我的 cellForRowAtIndexPath 的 tableView 函数

 override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("TestTableViewCell", forIndexPath: indexPath) as! TestTableViewCell

    let business = businessObjects[indexPath.row]

    if businessShown[indexPath.row] == false{
        self.getImageFromPhotoReference(business.businessPhotoReference) { (photo, error) -> Void in
            cell.backgroundImage.image = photo
        }
    }
    cell.businessNameLabel.text = business.businessName

    businessShown[indexPath.row] = true
    return cell
}


 func getImageFromPhotoReference(photoReference: String, completion: (photo: UIImage, error: NSError?) -> Void){
    let photoRequestParams = ["key":"##", "photoreference": photoReference, "maxheight": "800"]

    let placePhotoURLString = self.googleClient.buildPlacePhotoURLString(photoRequestParams)
    let photoRequestURL = NSURL(string: placePhotoURLString)!

    self.getDataFromUrl(photoRequestURL) { (data, response, error) -> Void in
        dispatch_async(dispatch_get_main_queue(), { () -> Void in
            guard let data = NSData(contentsOfURL: photoRequestURL) where error == nil else { return }
            let imageFile = UIImage(data: data)!

            completion(photo: imageFile, error: error)
        })
    }
}

private func getDataFromUrl(url: NSURL, completion: ((data: NSData?, response: NSURLResponse?, error: NSError? ) -> Void)) {
    NSURLSession.sharedSession().dataTaskWithURL(url) { (data, response, error) in
        completion(data: data, response: response, error: error)
        }.resume()
}

谢谢

最佳答案

问题是,当重用的单元已经在其上加载了新数据时,异步网络调用就会完成。我的建议是使用像 Kingfisher 或 HanekeSwift 这样的图像缓存实用程序,因为它们会自动取消单元重用时的异步调用,并缓存图像,从而减少网络调用。

关于ios - UITableView 单元格图像在滚动时不断切换单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35736228/

相关文章:

ios - 使用 GCD 实现并发读独占写模型

ios - 如何判断用户是否已在 iOS 上登录 Facebook?

ios - 在 View Controller 之间传递 FBSDK 登录管理器结果

uitableview - Swift - 如何对两种单元格类型使用 dequeueReusableCellWithIdentifier? (身份标识)

ios - viewWithTag:reloadData 后返回 nil

ios - 获取数据后移至 rootViewController

ios - 制作绿色的 UIActionSheet 按钮?

swift - UIButton 操作生成 SIGABRT 但没有断点触发器

Swift:为什么类方法有返回类型 AnyObject?

iphone - UIView 应该有多个 UITableViews 作为 subview