I have a table whose cells contain labels. Whenever I dequeue a reusable cell, the old labels are still lingering on it. I was able to remove them with this:
for(int a=[[newcell subviews]count]-1; a>=0;a--)
{
if([[[[newcell subviews]objectAtIndex:a]class] isSubclassOfClass:[UILabel class]])
{
[[[newcell subviews] objectAtIndex:a] removeFromSuperview];
}
}
But when I select the cell, I can see the old text on top of the new. I tried this:
[[newcell.selectedBackgroundView subviews] makeObjectsPerformSelector: @selector(removeFromSuperview)];
[[newcell.backgroundView subviews] makeObjectsPerformSelector: @selector(removeFromSuperview)];
But it didn’t work. How can I make the old labels disappear from the selected cell as well as the regular view of the cell?
This kind of problem tends to happen when you add subviews to your cells in
cellForRowAtIndexPath:regardless of whether it’s being dequeued or newly created. As a result, you end up creating a new subview each time the row is reused, and the old subviews accumulate.What you instead want to do is to use the same subview each time, but just set the relevant attributes (e.g., labels or color) each time. Check out the answers to How do I clear a cell completely when I reuse it? to see some possible approaches.