2014-02-28 132 views
5

在我的TableView中,我有一个NSMutableArray * currList的数据源 - 它包含对象代理的对象。我创建了自定义TableCell并正确设置了一切。我发现问题,而显示数据:iOS:自定义TableViewCell - 初始化自定义单元格

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 
    static NSString *simpleTableIdentifier = @"ChatListCell"; 

    // Custom TableViewCell 
    ChartListCell *cell = (ChartListCell *)[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier]; 

    if (cell == nil) { 
      // I believe here I am going wrong 
      cell = [[ChartListCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier]; 
      NSLog(@"Cell = %@", cell); // Shows null 
    } 
    /* 
    With UITableViewCell, things are working perfectly fine 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier]; 
    if (cell == nil) { 
     cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier]; 
    } 
    */ 
    Agent *agent = (Agent *)[currChatList objectAtIndex:indexPath.row]; 
    NSLog(@"Agent name - %@", agent.name); // Prints proper data 
    cell.nameLabel.text = agent.name; 
    cell.thumbImageView.image = [UIImage imageNamed:agent.photo]; 
    cell.timeLabel.text = agent.chatTime; 

    return cell; 
} 

正如你可以看到上面的代码中的注释,如果我评论的定制ChartListCell和使用的UITableViewCell,它工作正常。但与ChartListCell,什么都没有出现,在日志中我得到“Cell = null”&代理名称正确显示。 单元格不应该为空。为什么它是空的,任何人都可以请帮我解决这个问题。我在哪里做错了?

任何帮助,高度赞赏。

感谢

+1

你是否在代码中的其他地方注册了你的自定义细胞笔尖或类? – Alex

+0

当您使用ChartListCell时,单元格是否显示代理的名称/照片? – RaffAl

+0

你在哪里创建了这个自定义单元格?故事情节? XIB? – rdelmar

回答

14

导入您的自定义单元格的文件,并尝试这个

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

static NSString *simpleTableIdentifier = @"ChartListCell"; 

ChartListCell *cell = (ChartListCell *)[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier]; 
if (cell == nil) 
{ 
    NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"ChartListCell" owner:self options:nil]; 
    cell = [nib objectAtIndex:0]; 

}   

Agent *agent = (Agent *)[currChatList objectAtIndex:indexPath.row]; 
NSLog(@"Agent name - %@", agent.name); // Prints proper data 
cell.nameLabel.text = agent.name; 
cell.thumbImageView.image = [UIImage imageNamed:agent.photo]; 
cell.timeLabel.text = agent.chatTime; 

return cell; 
} 
+0

谢谢。我认为NSArray * nib是我犯错的那一行,但不知道错误是什么以及为什么需要NSArray *。从你的代码和问题 - “是否在Xib或故事板上创建”我可以让这一行是从xib文件初始化单元。但没有得到,为什么NSArray的NSArray&0th元素是单元格的对象?等待一段时间才能知道这一点,很快就会将答案标记为答案。使用第0个元素的 – Tvd

+2

,因为数组nib中只有一个元素。因为只有一个名为ChartListCell的nib文件 – Mohit

+1

好了,现在我理解了这些行的概念。我们从特定名称的包中获取xib文件然后从数组中选择特定的文件。数组将具有指定名称的所有文件,因为我们只有一个这样的名称的文件,我们从数组中选取第0个元素。非常感谢。 – Tvd

1

基本上有制作自定义UITableViewCells四种可能的方法: 如果你有兴趣了解所有这四个,这是值得通过这个链接: http://www.apeth.com/iOSBook/ch21.html#_custom_cells其中美妙地描述所有这些方法。

只是为了您的知识经历它。