Use different custom cells for each section in a UITableView

I found something strange was happening on my desk. I want to create a table with two or more partitions, and in the first section I want to use another custom cell with 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; } } 

In the first section, I want to use headerCell for my string, and then use detailCell for the rest. This code works, but the two-line section still uses headerCell "under" detailCell . I added a shortcut to headerCell.xib and it still displays on detailCell . See image .

I think all of this is because I use one cell identifier for the entire section. Anyone have a solution? Thank you very much.

+5
source share
1 answer

Each type of user cell must have its own unique identifier. Your code is trying to use the same cell id for all cells. This will not work.

Also register two types of cells in viewDidLoad , not cellForRowAtIndexPath:

Try the following:

 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]; } 
+9
source

Source: https://habr.com/ru/post/1236108/


All Articles