Nic Hubbard Nic Hubbard - 5 months ago 37
iOS Question

UITableViewCell subclass with UIImageView proper way to reuse

I have a

UITableViewCell
subclass. I want to add a
UIImageView
as a subview, but make sure to do proper reuse so that I am not adding the subview over and over. I also want to make sure to nil out the image in
prepareForReuse
.

What is the proper method for doing this?

Answer

In your custom cell subclass you should add any required views in the initWithStyle:reuseIdentifier: method. As long as you have registered your cell class against the reuse identifier in your table view then this initialiser will be called by dequeueReusableCellWithIdentifier:forIndexPath: whenever a new cell is required. This method will not be called when a cell is reused, so your image view won't be added more than once.

You can clear the image view's current image in the cell class's prepareForReuse method.