Fast cell image reuse

I am trying to get an image to show up in certain cells of my UITableView only under certain conditions. When the conditions are met, the image appears as expected, but when I scroll down the list, the icon appears in the cell at the bottom even though the condition was not met. I suppose this has a little something for the cell to be prototyped and reused in the code, but can't figure out how to fix it. Here is the code I have:

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
}

      

+3


source to share


2 answers


Add this to another:

cell.imageView?.image = nil

      



Explanation: UITableViews reuse cells. Because of this, you must set properties to account for both scenarios.

+6


source


Whenever you scroll through the table view, the cellForRowAtIndexPath method calls the new upcoming cell, and in this method you use the dequeueReusableCellWithIdentifier method to reuse the cell, then you get the old cell. This cell can have an image if you have already installed it. Therefore, you need to remove this image or install a new one as your requirement. From your code, you should remove the image using cell.imageView? .Image = nil in the else block.



0


source







All Articles