2010-08-31 26 views
1

有没有办法在tableViewController中使用多个uitableviewcell类与nib文件?在tableViewController中使用多个单元类

这是一个很棒的教程视频,介绍如何在cellForRowAtIndexPath函数中创建用于tableViewController的自定义单元类,我正在粘贴here以防万一任何人想看到。

在这个例子中,他们只使用一种可重用的单元类。这是来自我自己的项目,但它基本上是教程的内容。 “videoCellEntry”是我用nib文件videoEntryCell.xib创建的自定义单元格,“videoEntry”是我配置的每个单元的类,“videos”是videoEntry的数组。

我假设使用多个笔尖的文件,我可以把一些条件来选择我想要的笔尖文件,然后调用不同的loadNibNamed:部分像这样:

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

    static NSString *CellIdentifier = @"videoCellId"; 

    videoEntryCell *cell = 
    (videoEntryCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 

    if (cell == nil) { 
     if(<condition 1>) { 
      NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"videoEntryCell" owner:self options:nil]; 
     } 
     if(<condition 2>) { 
       NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"videoEntryCell2" owner:self options:nil]; 
     } 
cell = (videoEntryCell *)[nib objectAtIndex:0]; 
    } 

// Configure the cell. 
videoEntry *vid = [videos objectAtIndex:indexPath.row]; 
[cell configureForVideoEntry:vid]; 

    return cell; 
} 

但可以tableViewController处理多个细胞笔尖文件?或者,还有更好的方法?并不是每个单元格都需要一个不同的CellIdentifier,具体取决于它的nib文件吗?

回答

1

是的,您可以在TableViewController中使用多个Nib文件和多个CellIdentifiers。只要把你的条件放在CellIdentifier之前。我就是这样做的。

内侧一些示例 - (的UITableViewCell *)的tableView:(UITableView的*)的tableView的cellForRowAtIndexPath:(NSIndexPath *)indexPath方法:

首先定义可变单元:

UITableViewCell *cell; 

现在如果 - 块:

if(<condition 1>) { 
    static NSString *CellIdentifier = @"VideoCell1"; 
    cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
    if (cell == nil) { 
     NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"videoEntryCell" owner:nil options:nil]; 
     for (id currentObject in topLevelObjects){ 
      if([currentObject isKindOfClass:[UITableViewCell class]]){ 
       cell = (UITableViewCell *) currentObject; 
       break; 
      } 
     } 
    } 
    // customize your cell here 
} 

if(<condition 2>) { 
    static NSString *CellIdentifier = @"VideoCell2"; 
    cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
    if (cell == nil) { 
     NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"videoEntryCell2" owner:nil options:nil]; 
     for (id currentObject in topLevelObjects){ 
      if([currentObject isKindOfClass:[UITableViewCell class]]){ 
       cell = (UITableViewCell *) currentObject; 
       break; 
      } 
     } 
    } 
    // customize your cell here 
} 

最后:

return cell; 

您可以随意重复if-Block。这是唯一重要的是你返回一个单元格,这是而不是无。

+1

太棒了!感谢您的快速回复。我现在肯定尝试这个。 – Kennzo 2010-08-31 15:17:39

相关问题