Richa Srivastava Richa Srivastava - 27 days ago 7
Swift Question

UITableViewCell image is not showing properly on condition when scrolled

I have condition to show image for only few rows. But when I scroll, the image is shown for other random rows as well. Below is my code:

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath)
//var data = objectArray[indexPath.section].sectionObjects[indexPath.row] as? NSDictionary
if let data = objectArray[indexPath.section].sectionObjects[indexPath.row] as? NSDictionary{
if let name = data.objectForKey("NAME") as? String{
cell.textLabel?.text = name
}
if completedTrainings.contains((data.objectForKey("MENU_ID") as? Int)!) {
cell.imageView?.frame = CGRect(x: (cell.bounds.width-110), y: 0, width: 100, height: 100)
cell.imageView?.image = UIImage(named: "CORRECT")
}
}
return cell
}


Image should only appears if menu id exist in completed trainings but on scroll it appears on some random cells as well. Also the image is coming at the left but it should come at right. How can I move it to right?

Answer

since image is the optional for UIImageView u can set the image to nil if u dont want to display the image for example in your code, as vadian suggested

     cell.imageView?.image = nil //reset the cell image first
     cell.textLabel?.text  = "" 
     if let data = objectArray[indexPath.section].sectionObjects[indexPath.row] as? NSDictionary{
        if let name = data.objectForKey("NAME") as? String{
            cell.textLabel?.text = name
            cell.imageView?.image = nil //add this line
        }
        if completedTrainings.contains((data.objectForKey("MENU_ID") as? Int)!) {
            cell.imageView?.frame = CGRect(x: (cell.bounds.width-110), y: 0, width: 100, height: 100)
            cell.imageView?.image = UIImage(named: "CORRECT")
        }