1

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?

mattjgalloway
  • 34,792
  • 12
  • 100
  • 110
Josh Wight
  • 182
  • 1
  • 2
  • 8

3 Answers3

3

Subclass UITableViewCell (if you aren't already). Override prepareForReuse and remove the labels there. Might work

Markus Persson
  • 1,103
  • 9
  • 21
1

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.

Community
  • 1
  • 1
yuji
  • 16,695
  • 4
  • 63
  • 64
  • This was the problem for me (only on views that were added programmatically and not as IBOutlets) and I was able to fix it by doing the contentView.addSubview call in awakeFromNib of the UITableViewCell and then just changing that view's values depending on what each cell needed in cellForRowAtIndexPath – RanLearns Jul 19 '16 at 22:47
0

I kinda did what Yuji suggested. Instead of putting in new labels on each iteration, I checked whether the cell contained labels and then either edited the labels if they were there or put them in if they weren't. Code goes like this:

    if([[newcell.contentView subviews] count]>=2 && [[[[newcell.contentView subviews] objectAtIndex:0]class] isSubclassOfClass:[UILabel class]] && 
   [[[[newcell.contentView subviews] objectAtIndex:1]class] isSubclassOfClass:[UILabel class]])
{
    //change the text of the labels
}
else
{
    //add the labels to the cell
}
Josh Wight
  • 182
  • 1
  • 2
  • 8