Custom NSTableViewCell labels not appearing

I’m working on an iPhone app at the moment that is being upgraded from a previous version. I decided early on to just build on the existing code rather than trying to reinvent the wheel.

I’ve spent a bit of time fixing warnings that have cropped up from changes in the iOS SDK (the original app was developed for iOS 2) but one problem in particular had me stumped for a while.

When subclassing NSTableViewCell, the old init method was:

- (id)initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier

but somewhere along the line the init method definition changed to:

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

I’m yet to find out when this changed occurred, but it left me with the problem of no longer having access to the “frame” parameter. This meant the code in the init method that used to size the views of the custom cell no longer had a point of reference.

It took me a while to figure out that due to this change there was also another new method introduced that now had to be overridden to size the custom cell views:

-(void)layoutSubviews

In this method is where we are now meant to set the size of the custom cell views.

So I commented out the sizing code that used to be in the init method and moved it to the new layoutSubviews method as follows:

-(void)layoutSubviews
{
    [super layoutSubviews];
    CGRect label, steps;
    CGRect bounds = [[self contentView] bounds];
    label.origin.x = 20.0;
    label.origin.y = 3.0;
    label.size.height = bounds.size.height - (label.origin.y*2);
    label.size.width = 160.0;
    [dateLabel setFrame:label];

    steps.origin.x = 170.0;
    steps.origin.y = 5.0;
    steps.size.height = bounds.size.height - (steps.origin.y*2);
    steps.size.width = 120.0;
    [stepsLabel setFrame:steps];
}

This fixed my issue. Running the app now showed the custom cell labels as expected.