Swift 可重复使用的细胞图像被重复使用
Swift reusable cell image being reused
我试图让图像仅在特定条件下出现在我的 UITableView 的特定单元格中。满足条件时,图像会按预期显示,但是当我向下滚动列表时,即使不满足条件,也会在底部的单元格中看到图标。我 gessing 这与单元格是原型并在代码中重用有关,但无法弄清楚如何修复。这是我的代码:
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("locCell", forIndexPath: indexPath)
var currentLoc = self.hereLocs[indexPath.row]
var hereImage = UIImage(named: "loc")
if currentLoc.currentlyHere! == true {
cell.textLabel?.text = currentLoc.name!
cell.detailTextLabel?.text = currentLoc.vicinity!
cell.imageView?.image = hereImage
} else {
cell.textLabel?.text = currentLoc.name!
cell.detailTextLabel?.text = currentLoc.vicinity!
}
return cell
}
在 else 中添加:
cell.imageView?.image = nil
说明:
UITableViews 重用单元格。因此,您必须设置属性以考虑这两种情况。
每当你滚动 tableview 然后 cellForRowAtIndexPath 方法调用新的即将到来的单元格,并且在这个方法中你使用 dequeueReusableCellWithIdentifier 方法重用单元格然后你将得到一个旧单元格。如果您之前在该单元格上设置过,则该单元格可以包含图像。因此,您必须根据需要删除此图像或设置新图像。从您的代码中,您应该在 else 块中使用 cell.imageView?.image = nil 删除图像。
我试图让图像仅在特定条件下出现在我的 UITableView 的特定单元格中。满足条件时,图像会按预期显示,但是当我向下滚动列表时,即使不满足条件,也会在底部的单元格中看到图标。我 gessing 这与单元格是原型并在代码中重用有关,但无法弄清楚如何修复。这是我的代码:
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("locCell", forIndexPath: indexPath)
var currentLoc = self.hereLocs[indexPath.row]
var hereImage = UIImage(named: "loc")
if currentLoc.currentlyHere! == true {
cell.textLabel?.text = currentLoc.name!
cell.detailTextLabel?.text = currentLoc.vicinity!
cell.imageView?.image = hereImage
} else {
cell.textLabel?.text = currentLoc.name!
cell.detailTextLabel?.text = currentLoc.vicinity!
}
return cell
}
在 else 中添加:
cell.imageView?.image = nil
说明: UITableViews 重用单元格。因此,您必须设置属性以考虑这两种情况。
每当你滚动 tableview 然后 cellForRowAtIndexPath 方法调用新的即将到来的单元格,并且在这个方法中你使用 dequeueReusableCellWithIdentifier 方法重用单元格然后你将得到一个旧单元格。如果您之前在该单元格上设置过,则该单元格可以包含图像。因此,您必须根据需要删除此图像或设置新图像。从您的代码中,您应该在 else 块中使用 cell.imageView?.image = nil 删除图像。