我很好奇如何正确地使用xib文件来布局UITableViewCell的内容。当我尝试按照在互联网上找到的所有步骤进行时,我总是会遇到以下错误:
在我的UIViewController中,我尝试了两种方法
或者使用
这两种方法都无法避免标题中提到的异常。 owner:self 的异常是因为 UIViewController 没有 IBOutlet 属性,而 owner:nil 的异常是因为它内部使用的是 NSObject,这个类也没有 IBOutlet 属性。
我找到的唯一变通方法如下。在我的单元格的 init 方法中,我将返回的视图/单元格添加到我的初始化单元格中。
例如:
Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<NSObject 0x10fe7d790> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key statusLabel.'
这里是相关的代码:
@interface MyCell : UITableViewCell
@property (nonatomic,strong) IBOutlet UILabel* messageLabel;
@property (nonatomic,strong) IBOutlet UILabel* statusLabel;
在我的UIViewController中,我尝试了两种方法
-(void)viewDidLoad {
[self.tableView registerNib:[UINib nibWithNibName:@"MyCell"
bundle:[NSBundle mainBundle]]
forCellReuseIdentifier:@"CustomCellReuseID"];
}
或者使用
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"CustomCellReuseID";
MyCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if ( !cell ) {
cell = [[[NSBundle mainBundle] loadNibNamed:@"MyCell" owner:self options:nil]
lastObject];
// or sometimes owner is nil e.g.
//cell = [[[NSBundle mainBundle] loadNibNamed:@"MyCell" owner:nil options:nil]
lastObject];
}
// ... remainder of cell setup
return cell;
}
这两种方法都无法避免标题中提到的异常。 owner:self 的异常是因为 UIViewController 没有 IBOutlet 属性,而 owner:nil 的异常是因为它内部使用的是 NSObject,这个类也没有 IBOutlet 属性。
我找到的唯一变通方法如下。在我的单元格的 init 方法中,我将返回的视图/单元格添加到我的初始化单元格中。
例如:
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
// nil out properties
[self.contentView addSubview:[[[NSBundle mainBundle] loadNibNamed:@"MyCell" owner:self options:nil] lastObject]];
}
return self;
}
这似乎非常可疑(虽然我也可以将 xib 的基础类型更改为 UIView 而不是 MyCell 或 UITableViewCell),这使它感觉稍微不那么可疑。
我看到了许多人遇到了这个特定的错误。通常会将其解释为 xib 本身的连线问题,但如果我在 xib 中删除所有连接,它可以正常加载,但一旦我重新添加一个 ui 元素和文件所有者之间的连接,错误就会返回,所以我不认为这与“清理”xib有任何关系(即使查看 xib 的 XML,也没有列出任何错误的连接)。
还有其他人对此错误有什么想法吗?