I’m trying to print a UITableView with two distinct types of UITableViewCells.
- Empty table view cells that contains nothing (first 2 cell), just a black background
- Table view cells that contains a label, an image, etc. beginning from 1 (3rd and subsequent cells)
The height of my table view is able to fit at least 3 table view cells at anyone time.
When I first load the table view, the table view looks perfectly fine – 1st two rows are black, follow by the 3rd row which has the label that says “1”.
However, after scrolling down to the bottom then scrolling back up. My first two empty cells (which are supposed to be empty) are filled with things that should only be found in the 3rd and subsequent cells.
I suspect this behavior is coming from the table view reusing cells but I’m still unable to figure it out.
Code snippets:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
}
switch ([indexPath row]) {
case 0:
cell.contentView.backgroundColor = [UIColor blackColor];
[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
break;
case 1:
cell.contentView.backgroundColor = [UIColor blackColor];
[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
break;
default:
cell.contentView.backgroundColor = [UIColor blackColor];
[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
UILabel *rowLabel = [[UILabel alloc] initWithFrame:CGRectMake(25, 30, 200, 30)];
rowLabel.text = [NSString stringWithFormat:@"Row %d", [indexPath row]-1];
rowLabel.backgroundColor = [UIColor blackColor];
rowLabel.textColor = [UIColor whiteColor];
[rowLabel setFont:[UIFont fontWithName:@"GillSans-Bold" size:18]];
[cell.contentView rowLabel]; [rowLabel release];
UIButton *aButton = [[UIButton alloc] initWithFrame:CGRectMake(100, 50, 40, 40)];
[aButton setImage:anImage forState:UIControlStateNormal];
[cell.contentView addSubview:aButton];
[aButton release];
break;
}
return cell;
}
Your dequeued cells will still contain all of the buttons and labels you added, all you are doing is setting the background colour when the cell is dequeued.
You have a few options:
tableHeaderViewfor your black areaFor the latter option, your
cellForRowAtIndexPathshould be: