Reputation: 1579
I have 9 rows in my tableview and want to add buttons to only row 1 and 2. When first time the code runs, it shows button on 1 and 2. But when I scroll the tableview, it starts randomly showing for row 4,5,8,9. The code is below. Please advice what I am doing wrong.
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView
dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc]
initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:CellIdentifier];
}
cell.textLabel.text = [NSString stringWithFormat:@"Row %d",[indexPath row]];
if([indexPath row] == 0 || [indexPath row] == 1)
{
cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;
}
return cell;
}
Upvotes: 0
Views: 55
Reputation: 318774
This is a common mistake. When you want something in only some cells, you need to reset the value in the other cells.
if([indexPath row] == 0 || [indexPath row] == 1) {
cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;
} else {
cell.accessoryType = UITableViewCellAccessoryNone;
}
Basically, for any given cell identifier, you need to set the same set of properties for every index path. If you only set a property for some index paths, then as the cells get reused you will start seeing issues.
Upvotes: 3