I have a basic UITableView with four sections. I control the content in each section with a Switch statement.
I programmatically create a button, which should appear in the rows of the first THREE sections, but should NOT appear in the fourth. However, the button is appearing randomly in the fourth section’s rows.
I presume this is because a cell is being reused, but as I create each section’s rows with the Switch statement, I cannot see how this is happening. Any ideas appreciated.
I am using a custom cell configured so:`
static NSString *CustomCellIdentifier = @"DashboardCell";
DashboardCell *cell = (DashboardCell *)[tableView dequeueReusableCellWithIdentifier: CustomCellIdentifier];
if (cell == nil) { NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"DashboardCell"
owner:self options:nil];
for (id oneObject in nib) if ([oneObject isKindOfClass:[DashboardCell class]])
cell = (DashboardCell *)oneObject;
}
// Configure the cell.`
The code to create this button is: `
button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake(200, 11, 50, 50);
UIImage *iConnect = [UIImage imageNamed:@"connect.png"];
[button setImage:iConnect forState:UIControlStateNormal];
[button addTarget:self action:@selector(buttonSelected:) forControlEvents:UIControlEventTouchUpInside];
[cell addSubview:button];`
You need a different reuse identifier for each type of content. So here you have two types of content – cell’s that have a
UIButtonand cells that don’t.Use the
indexPathof thetableView:cellForRowAtIndexPath:method to select a reuse identifier of either @”CellWithButton” or @”CellWithoutButton”.What is actually happening in your code is that all cells are given the same reuse identifier, meaning that they all get put into the same object pool. This means that when you use
[tableView dequeueReusableCellWithIdentifier: CustomCellIdentifier];that you are retrieving a cell from this one pool (which potentially contains cells that have noUIButtonand cells that do). Therefore the dequeue method can randomly return a cell that has already had aUIButtonadded to it. If you use two reuse identifiers, theUITableViewwill setup two object pools and will correctly deposit and retrieve the appropriate cells from each.Or you can use one reuse pool and check the cell for a
UIButtoneach time you retrieve one using the dequeue method.