2016-03-02 98 views
0

当我有对象的数组(其中包括必需的数据下载从谷歌商家API照片),当我尝试加载这些对象的元件中的tableView细胞,图像以及titleLabels在滚动时继续切换。UITableView的细胞图像保持对开关单元滚动

这里是的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() 
} 

谢谢

回答

0

的问题是异步网络时重用细胞已加载在它之上的新数据调用完成。我的建议是使用像Kingfisher或HanekeSwift这样的图像缓存工具,因为它们可以自动取消对信元重用的异步调用,并且还可以缓存图像,从而减少网络调用次数。

+0

HanekeSwift是完美的背景图像!非常感谢你! – user3796209

0

你的代码是不是线程安全的,至少你应该检查在完成处理程序,您正试图填补与图像单元格是否仍然在同一个位置,当你开始异步图像加载它。例如,您可以设置等于项目编号细胞视图标签,如果你下载的图像,但电池的标签已经改变,不要碰这个小区