Search code examples
iosobjective-cuitableviewcell-formatting

How to add 2 different custom cells in cellforrow?


I have issue, my app crash on cellForRowAtIdexPath because I want to add 2 different custom table view cells for 2 different rows.

See my code.

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier1 = @"MatchDetail";
MatchDetailsCell *cell1 = [tableView dequeueReusableCellWithIdentifier:CellIdentifier1];

static NSString *CellIdentifier2 = @"GoalsList";
GoalsListCell *cell2 = [tableView dequeueReusableCellWithIdentifier:CellIdentifier2];

if(indexPath.section == 0)
{
    if(indexPath.row == 0)
    {
        if (cell1 == nil) {
            cell1 = (MatchDetailsCell *)[MatchDetailsCell cellFromNibNamed:@"MatchDetailsCell"];
        }
        [cell1 setDataInCell:arrAllGames :strTeamA :strTeamB];
        return cell1;
    }
    else if (indexPath.row == 1)
    {
        if (cell2 == nil) {
            cell2 = (GoalsListCell *) [GoalsListCell cellFromNibNamed:@"GoalsListCell"];
        }
        [cell2 setDataInCell:arrGoalsList :[arrAllGames count]];
        return cell2;
    }
}

return nil;

}


Solution

  • Your code is incorrect. You must dequeue the cell of this row with this identifier. If you have only one section in the table, you don't need to do the indexPath.section check. Try this:

    -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
        static NSString *CellIdentifier1 = @"MatchDetail";
        static NSString *CellIdentifier2 = @"GoalsList";
        if(indexPath.row == 0) {
             //The first row is the MatchDetailsCell
             MatchDetailsCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier1];
             if(cell == nil) {
                //If cell not exists, you must create a new one
                cell = [[MatchDetailsCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier1];
             }
             //Rest of your cell code here
             return cell;
        } else {
             //Rest of the cells are GoalsListCell
             GoalsListCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier2];
             if(cell == nil) {
                 cell = [[GoalsListCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier2];
             }
             //Rest of your cell code here
             return cell;
        }
    
    }
    

    I don't have more information about your code, but maybe it helps you.