Xcode 5,Dynamic Prototype的自定义UITableViewCell类

Tim*_*van 0 xcode objective-c interface-builder ios

我正在使用Xcode 5,并希望使用Apple推荐的最佳实践,包括动态原型单元和使用registerClass:forCellReuseIdentifier.

我创建了一个故事板并在其UITableView上放置了一个原型动态单元格.我已将单元格的类设置为ItemCell,并将重用标识符设置为ItemCell.

ItemCell类包含一个nameLabelIBOutlet,我通过拖动将其连接到原型单元格中的标签.

在ViewController中,我注册了ItemCell要用于ItemCell重用标识符的类:

- (void)viewDidLoad {
    [super viewDidLoad];

    [_tableView registerClass:[ItemCell class] forCellReuseIdentifier:@"ItemCell"];
}
Run Code Online (Sandbox Code Playgroud)

在tableView:cellForRowAtIndexPath中,我将单元格出列并设置nameLabel的属性.self.items是一个NSArray字符串.

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
        ItemCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ItemCell" forIndexPath:indexPath];
        cell.nameLabel.text = [self.items objectAtIndex:indexPath.row];

        return cell;
}
Run Code Online (Sandbox Code Playgroud)

所以:它是作为ItemCell创建的,但它并没有从故事板中加载它.我已经通过重写initWithStyle来确认这一点:reuseIdentifier和initWithCoder,以查看被调用的内容:

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        // Initialization code
        NSLog(@"NOT STORYBOARD");
    }
    return self;
}

-(id)initWithCoder:(NSCoder *)aDecoder {
    self = [super initWithCoder:aDecoder];
    if (self) {
        // Initialization code
        NSLog(@"Yay, it's working!");
    }
    return self;

}
Run Code Online (Sandbox Code Playgroud)

每一次,它都initWithStyle被称为.从我读过的所有内容来看,这应该是有效的.我找不到任何表明我需要以不同的方式在故事板中注册该类的东西,但很明显,单元格并不知道它有一个与之相关的故事板.

我确定我总是犯了一个新手的错误,但我无法弄明白.任何帮助,将不胜感激.

Mar*_*n R 8

您不必(也不应该)调用registerClass故事板中定义的原型单元格.initWithCoder如果必须从故事板中实例化原型单元,则会自动调用.