2012-08-15 146 views
2

我在创建自定义UITableViewCell时遇到了难以置信的难度。我已经彻底检查了stackoverflow和google,但是发布的所有解决方案都不完整,不正确,或者做得足够远。如何正确连接自定义UITableViewCell并访问元素

所以这就是我想要做的。我想让MyTableViewController在自定义单元格中加载,我们称它们为MyCustomCell,而不是默认单元格。我希望MyCustomCell是UITableViewCell的一个完整的子类,所以我只有一个带有UITableViewCell的(.xib)和一些测试标签。单元格标识符被设置为“MyCustomCell”,并且该类别被设置为“MyCustomCell”。我可以将标签拖放到MyCustomCell.h中。

回到MyTableViewController.m,我有下面的代码

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

MyCustomCell *cell = [tableView dequeueReusableCellWithIdentifier:ident];//appears to crash here 
if(cell == nil){ 
    NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:ident owner:self options:nil]; 
    for(id currentObject in topLevelObjects){ 
     if([currentObject isKindOfClass:[MyCustomCell class]]){ 
      cell = (MyCustomCell*)currentObject; 
      break; 
     } 
    } 
} 
cell.myCustomLabel.text = @"hello world";//myCustomLabel from the .xib is linked up to the 
//proper variable in MyCustomCell.h, and it's also being synthesized 
//I'd like to modify all the custom labels,imageviews,etc here 
return cell; 
} 

运行这给了我以下错误:

Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<MyTableViewController 0x7d5ba80> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key myCustomLabel.' 

这通常出现在当我忘了勾一些.xib和它的.h文件,或者当它不合成,但我已经检查,似乎工作。有什么我在这里做错了吗?我必须完成[[MyCustomCell alloc] init]或[[MyCustomCell alloc] initWithCustomMethod:...]吗?

回答

1

如果你的目标的iOS 5,使用:

[self.tableView registerNib:[UINib nibWithNibName:@"yourNibName" bundle:nil] forCellReuseIdentifier:@"yourNibIdentifier"]; 

然后,你只需要使用标识符从笔尖获得细胞

[tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 

最后:确保你实际上是为你的UITableViewCell子类的nib分配适当的类名和适当的标识符。

+0

你的第一个建议似乎没有奏效。我也再次越过了笔尖,一切看起来都应该起作用。最后,我刚刚删除了所有内容,从头开始,现在看起来好像一切正​​常 – user1601540 2012-08-15 23:45:51

相关问题