如何为一个表视图加载两个自定义tableview单元格

时间:2016-02-03 13:06:34

标签: ios

我想使用两个自定义tableviewcells(两个nib文件),例如第一行的第一个自定义视图和第二行的第二个自定义视图。但是第一个tableviewcell没有加载。每行仅显示第二行。以下是我使用的代码,

在viewdidload中,我注册了

UINib *nib = [UINib nibWithNibName:@"TableViewCell" bundle:nil];
[self.mainTableView registerNib:nib forCellReuseIdentifier:CellIdentifier1];

nib = [UINib nibWithNibName:@"SecondTableViewCell" bundle:nil];
[self.mainTableView registerNib:nib forCellReuseIdentifier:CellIdentifier2];


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

 //UITableViewCell *cell;

static NSString *CellIdentifier1 = @"TableViewCell";
static NSString *CellIdentifier2 = @"SecondTableViewCell";


if (indexPath == 0) {
   TableViewCell *cell = (TableViewCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier1];
        return cell;
} else {
  SecondTableViewCell*  cell = (SecondTableViewCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier2];
        // Load the top-level objects from the custom cell XIB.
        cell.questionLbl.text = [NSString stringWithFormat:@"%ld",indexPath.row+1];
        //cell.questionName.text = [self.questionsArray objectAtIndex:indexPath.row];
        // Grab a pointer to the first object (presumably the custom cell, as that's all the XIB should contain).
        return cell;
}


return nil;
}

3 个答案:

答案 0 :(得分:1)

1)更改此行将起作用

if (indexPath.row == 0) { 
TableViewCell *cell = (TableViewCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier1];
        return cell;
}

2)每次返回带有identifier2的单元格,因为indexPath不会是nil

答案 1 :(得分:0)

索引路径不是数字。测试if (indexPath == 0)表示“如果没有indexPath”。

尝试indexPath.row

答案 2 :(得分:0)

尝试indexpath.row。 如果你使用if(indexpath == 0),它将不会检查行值。