覆盖自定义单元格 initWithStyle 方法但未被调用

Overriding custom cell initWithStyle method but it's not being called

我有一个自定义的 UITableViewCell,我想像下面这样覆盖 init 方法:

-(id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {

    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    self.buttons = [[NSMutableArray alloc] initWithObjects:self.button1, self.button2,self.button3,self.button4, nil];
    self.labels = [[NSMutableArray alloc] initWithObjects:self.label1,self.label2,self.label3,self.label4, nil];
    NSLog(@"init done");
    return self;
}

我需要这种方法来将我的按钮和标签放入数组中。我正在使用以下代码创建单元格:

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

    FriendViewCell *cell = (FriendViewCell *)[tableView dequeueReusableCellWithIdentifier:@"friendCell" forIndexPath:indexPath];

}

但是没有调用 init 方法并且数组为 nil。不确定发生了什么!我是否覆盖了正确的方法?

仅当您显式调用此初始化程序时才会调用它。如果您从 nib/storyboard 加载单元格,则不会调用它。

通常,我们重写 awakeFromNib 方法来自定义从 nib 加载的单元格。

- (void)awakeFromNib {
    [super awakeFromNib];

    self.buttons = [[NSMutableArray alloc] initWithObjects:self.button1, self.button2, self.button3, self.button4, nil];
    self.labels = [[NSMutableArray alloc] initWithObjects:self.label1, self.label2, self.label3, self.label4, nil];
}

另一个注意事项 - 您可以使用 IBOutletCollection,例如

,而不是从 button1button2 等创建 buttons 数组
@property (nonatomic) IBOutletCollection NSArray *buttons;

并直接从 Interface Builder 连接按钮,但请注意它不会以任何特定顺序保留对象。

您可以尝试使用- (id)initWithCoder:(NSCoder *)aDecoder

还要确保您没有忘记为 Interface Builder 中的单元格设置自定义 class(我假设您 "defined" IB 中的自定义单元格)。