Alf*_*fro 4 asynchronous uitableview swift xcode7 swift2
当我在tableView Controller中填充新数据时,我的顶部单元格正在被底部单元格重写.让我解释.我有一个图像在底部的最新单元格行中加载异步.所有其他单元格都使用应用程序中的图像加载静态.当我向下滚动我的应用程序并显示与其他单元格图像不同的底部单元格时,我再次向上滚动,我看到第一个商店图像已更改为底部单元格中加载的动态图像.有谁知道为什么会这样?
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell : shopsTableViewCell = tableView.dequeueReusableCellWithIdentifier("shopCell", forIndexPath: indexPath) as! shopsTableViewCell
cell.index = indexPath.row
let qualityOfServiceClass = QOS_CLASS_BACKGROUND
let backgroundQueue = dispatch_get_global_queue(qualityOfServiceClass, 0)
let apiCall = webApi()
dispatch_async(backgroundQueue, {
apiCall.downloadPhotoAsync("http://api-ytyg.wbbdev.com/files/shops/\(shops[indexPath.row].id)/\(shops[indexPath.row].featured_img)"){(image: UIImage?) -> Void in
dispatch_async(dispatch_get_main_queue()){
if(image != nil){
if (cell.index == indexPath.row){
// shops[indexPath.row].photo = image!
cell.shopImg?.image = image
}
}else{
shops[indexPath.row].photo = UIImage.init(named: "No_Image_Available.jpg")!
}
}
}
})
cell.shopName?.text = shops[indexPath.row].name
cell.shopDescription?.text = shops[indexPath.row].address
cell.label1?.text = shops[indexPath.row].city + " | " + shops[indexPath.row].distance + "Km"
cell.becomeFirstResponder()
return cell
}
Run Code Online (Sandbox Code Playgroud)
这是因为你的细胞被重用:
// this line initialize a cell of type shopsTableViewCell
//if no cell can be reused, get an already used cell else
let cell : shopsTableViewCell
= tableView.dequeueReusableCellWithIdentifier("shopCell",
forIndexPath: indexPath) as! shopsTableViewCell
Run Code Online (Sandbox Code Playgroud)
因此,图像和其他数据应该是出列单元格的最后一个图像和数据.
为避免这种情况,您应prepareForReuse在单元类文件中实现重置数据和图像.关于prepareForReuse func的苹果文档
来自Apple文档:
如果UITableViewCell对象是可重用的 - 也就是说,它具有重用标识符 - 在从UITableView方法dequeueReusableCellWithIdentifier:返回对象之前调用此方法.出于性能原因,您应该仅重置与内容无关的单元格属性,例如,alpha,编辑和选择状态.tableView中的表视图委托:cellForRowAtIndexPath:在重用单元格时应始终重置所有内容.如果单元对象没有关联的重用标识符,则不会调用此方法.如果重写此方法,则必须确保调用超类实现.
//Example :
override func prepareForReuse() {
super.prepareForReuse()
//Do reset here
this.shopImg?.image = nil
this.shopName?.text = ""
this.shopDescription?.text = ""
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5087 次 |
| 最近记录: |