ios - 如何在 cellforrow 中添加 2 个不同的自定义单元格?

标签 ios objective-c uitableview cell-formatting

我有问题,我的应用程序在 cellForRowAtIndexPath 上崩溃,因为我想为 2 个不同的行添加 2 个不同的自定义表格 View 单元格。

查看我的代码。

-(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;

最佳答案

您的代码不正确。您必须使用此标识符将此行的单元格出列。 如果表中只有一个部分,则不需要进行 indexPath.section 检查。试试这个:

-(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;
    }

}

我没有关于你的代码的更多信息,但也许它对你有帮助。

关于ios - 如何在 cellforrow 中添加 2 个不同的自定义单元格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25284496/

相关文章:

ios - 为 NSNotificationCenter 添加乘法观察者

swift - 如何在间隔 TableView 单元格中正确显示数据

iphone - 是否有用于取消自动续订订阅的 API?

ios - 在另一个应用程序中打开文件时更改 UIDocumentInteractionController 中的文件名

iphone - NSPredicate 以多个文件结尾

ios - NSDictionary 到 NSMutableArray

ios - Tableview 中的 Swift Firebase Firestore 数据

ios - 我不确定如何将 RSS 提要中的图像添加到我的 UITableView 中

android - 边框在 Android 4+ 和 iOS 6.0 上不以 border-radius flex

objective-c - 已弃用的 userInfo 字典键的可移植代码 (Cocoa)