样式自定义UITableViewCell在initWithCoder:不工作



我有一些问题与自定义UITableViewCell和如何管理使用故事板的事情。当我把样式代码在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;
}

我已经调试了代码,发现dequeue...首先被调用,然后它进入initWithCoder:,然后返回到视图控制器代码。奇怪的是,内存中单元格的地址在return self;和返回控制器之间发生变化。如果我把样式代码移回dequeue...之后的视图控制器,一切都很好。我只是不想在重用单元格时做不必要的样式。

欢呼

在单元格上调用initWithCoder:之后,将创建单元格并设置其属性。但是,单元格上的XIB (IBOutlets)中的关系尚未完成。因此,当你试图使用mainLabel时,它是nil的引用。

将样式代码移到awakeFromNib方法中。在解包XIB后创建单元格并完全配置单元格后调用此方法。

最新更新