在initWithCoder中自定义UITableViewCell的样式:不起作用

我有一个自定义UITableViewCell的问题,以及如何使用故事板pipe理事情。 当我把样式代码放在initWithCoder:它不起作用,但如果我把它放在tableView: cellForRowAtIndexPath:它的作品。 在故事板中,我有一个类属性设置为我的UITableViewCell自定义类的原型单元格。 现在initWithCoder:的代码被调用了。

SimoTableViewCell.m

 @implementation SimoTableViewCell @synthesize mainLabel, subLabel; -(id) initWithCoder:(NSCoder *)aDecoder { if ( !(self = [super initWithCoder:aDecoder]) ) return nil; [self styleCellBackground]; //style the labels [self.mainLabel styleMainLabel]; [self.subLabel styleSubLabel]; return self; } @end 

TableViewController.m

 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"NearbyLandmarksCell"; SimoTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath]; //sets the text of the labels id<SimoListItem> item = (id<SimoListItem>) [self.places objectAtIndex:[indexPath row]]; cell.mainLabel.text = [item mainString]; cell.subLabel.text = [item subString]; //move the labels so that they are centered horizontally float mainXPos = (CGRectGetWidth(cell.contentView.frame)/2 - CGRectGetWidth(cell.mainLabel.frame)/2); float subXPos = (CGRectGetWidth(cell.contentView.frame)/2 - CGRectGetWidth(cell.subLabel.frame)/2); CGRect mainFrame = cell.mainLabel.frame; mainFrame.origin.x = mainXPos; cell.mainLabel.frame = mainFrame; CGRect subFrame = cell.subLabel.frame; subFrame.origin.x = subXPos; cell.subLabel.frame = subFrame; return cell; } 

我debugging了代码,发现dequeue...被调用,然后进入initWithCoder:然后返回到视图控制器代码。 奇怪的是,内存中单元格的地址在return self;之间变化return self; 当它回到控制器。 如果我在dequeue...之后将样式代码移回视图控制器dequeue...一切正常。 这只是我不想在重复使用单元格时做不必要的样式。

干杯

在单元格上调用initWithCoder:之后,将创build单元并设置其属性。 但是,单元格上的XIB(IBOutlets)中的关系还没有完成。 所以当你尝试使用mainLabel ,它是一个nil参考。

相反,将您的样式代码移动到awakeFromNib方法。 这个方法是在解包XIB之后创build并完全configuration单元后调用的。