【问题标题】:How to properly link up a custom UITableViewCell and access elements如何正确链接自定义 UITableViewCell 和访问元素
【发布时间】:2012-08-15 21:48:41
【问题描述】:

我在创建自定义 UITableViewCell 时遇到了难以置信的困难。我已经彻底检查了 stackoverflow 和 google,但发布的所有解决方案要么不完整、不正确,要么做得不够。

这就是我想要做的。我想在自定义单元格中加载 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:...] 吗?

【问题讨论】:

    标签: objective-c ios uitableview


    【解决方案1】:

    如果您的目标是 iOS 5,请使用:

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

    然后,您只需使用标识符从笔尖获取单元格

    [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    

    最后:确保您实际上为 UITableViewCell 子类的 nib 分配了正确的类名和正确的标识符。

    【讨论】:

    • 您的第一个建议似乎不起作用。我也再次检查了笔尖,一切看起来都应该可以工作。最后,我只是删除了所有内容,重新开始,现在看起来一切都刚刚好
    猜你喜欢
    • 1970-01-01
    • 2017-10-25
    • 1970-01-01
    • 2019-06-22
    • 1970-01-01
    • 2014-06-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多