Search code examples
iosswiftuitableviewuiviewcontrollerpull-to-refresh

UITableView cells getting corrupted upon scrolling


In my iOS app, I'm dealing with a glitch in my UITableView. Each cell in my table view contains three icons (three little images representing a skateboard, bike, and rollerblade). Check out a screenshot of this table view by looking at the first app screenshot here and you'll see what I'm talking about.

These three icons that show up in every cell of my table view are "tinted" either black or grey depending on a boolean value that is retrieved asynchronously from an API call. So far while using the app, every cell has always had all three icons tinted black so I've never ran into any problems...until I tested what happens when one of the icons is meant to be grey.

When all of the icons are black, there's no issues. When just one icon in one cell is meant to be grey, all hell breaks loose. Initially the table view will load up fine and there will only be one greyed out icon. But then when you scroll down or pull to refresh the table view, all of a sudden other cells begin to contain grey icons when they are not meant to. The cells get more and more corrupted as you scroll up and down and eventually most of the cells have grey icons when only one cell really should. It's weird...it's like the one grey icon is multiplying and infecting my table view lol.

The problem here is that I clearly don't know how to properly use and update cells in the UITableView. I really don't know what the issue is. I'm not all that experienced in iOS dev. My code is pretty darn sloppy and somewhat embarrassing, but I'd appreciate it if you'd look through it and tell me what I'm doing wrong.

View the code related to this problem here. Thanks for the help!


Solution

  • You need to set UIImageView.image to different colour according to your bool value.

    if (!parkForIndexPath(indexPath).skateboardersAllowed()) {
        skateboardIcon.image = skateboardIcon.image?.imageWithColor(UIColor.darkGrayColor())
    } else {
        skateboardIcon.image = skateboardIcon.image?.imageWithColor(UIColor.blackColor())
    }
    

    The reason for some of your image becomes grey during scrolling is because you reuse the cell, so when the cell with grey image get reused, the grey image will still persist since you aren't resetting the colour.