Reputation: 1248
I found some strange happens on my table. I want to create table with two or more section, and on the first section I want to use different custom cell with the others.
So I created this on my tableView:cellForRowAtIndexPath
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellIdentifier = @"cell";
if (indexPath.section == 0) {
// cell for section one
HeaderCell *headerCell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if(!headerCell) {
[tableView registerNib:[UINib nibWithNibName:@"HeaderCell" bundle:nil] forCellReuseIdentifier:cellIdentifier];
headerCell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
}
headerCell.labelName.text = @"First Section";
return headerCell;
}
else {
// Cell for another section
DetailCell *detailCell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (!detailSection) {
[tableView registerNib:[UINib nibWithNibName:@"DetailCell" bundle:nil] forCellReuseIdentifier:cellIdentifier];
detailCell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
}
detailCell.textLabel.text = @"Another Section Row";
return detailCell;
}
}
On the first section, I want to use headerCell
for my row, then use detailCell
on the others. This code works but on the section two's row looks like still using headerCell
"under" detailCell
. I added label into headerCell.xib
, and it still shown on the detailCell
. See this image.
I think all of this because I use one cell identifier for all of section. Anyone have solution? Thank you so much.
Upvotes: 5
Views: 6044
Reputation: 318804
Each type of custom cell should have its own unique identifier. Your code is attempting to use the same cell identifier for all cells. That won't work.
Also, register the two cell types in viewDidLoad
, not cellForRowAtIndexPath:
.
Try this:
static NSString *cellIdentifier0 = @"cell0";
static NSString *cellIdentifier1 = @"cell1";
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
if (indexPath.section == 0) {
// cell for section one
HeaderCell *headerCell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier0 forIndexPath:indexPath];
headerCell.labelName.text = @"First Section";
return headerCell;
} else {
// Cell for another section
DetailCell *detailCell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier1 forIndexPath:indexPath];
detailCell.textLabel.text = @"Another Section Row";
return detailCell;
}
}
- (void)viewDidLoad {
[super viewDidLoad];
// the rest of your code
[self.tableView registerNib:[UINib nibWithNibName:@"HeaderCell" bundle:nil] forCellReuseIdentifier:cellIdentifier0];
[self.tableView registerNib:[UINib nibWithNibName:@"DetailCell" bundle:nil] forCellReuseIdentifier:cellIdentifier1];
}
Upvotes: 10