I am adding a custom button into my cell.contentView, and I noticed that every time a cell is scrolled off the visible part of the screen and back on, the button gets re-added – the translucent parts of it get more and more solid. What is the correct way to handle it so that it does not keep stacking more objects on top when scrolling through the tableView? Note that custom content is different for each cell, so I cannot put it into the if (cell == nil) {...} block.
The code I have is:
UISegmentedControl *btn = [[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObject:btn_title]];
// set various other properties of btn
...
[cell.contentView addSubview:btn];
Every time the cell is dequeued, you have to remove the old subviews before adding new ones, or else you’ll get that stacking effect. You can do this in one of two places:
a) In
tableView:cellForRowAtIndexPath:, remove your old views after thedequeueReusableCellWithIdentifier:call and before adding your new ones.b) If you’re using a subclass of
UITableViewCell, you can overrideprepareForReuseto remove unwanted views.prepareForReuseis called every time a cell is dequeued for reuse, so it’s a good place to get rid of old views from the last time the cell was configured.