Styling a custom UITableViewCell in initWithCoder: not working

I have some problems with a custom UITableViewCell and how to manage things with a storyboard. When I put the style code in initWithCoder: it does not work, but if I put it in tableView: cellForRowAtIndexPath: it works. In the storyboard, I have a prototype with my class attribute set to a custom class UITableViewCell. Now the code in initWithCoder: is called.

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; } 

I debugged the code and found that dequeue... is called first, then it goes into initWithCoder: and then back to the view controller code. It is strange that the address of a cell in memory changes between return self; and when he returns to the controller. And if I return the style code back to the view controller after dequeue... everything will be fine. I just don’t want to make unnecessary style when reusing cells.

Greetings

+7
source share
1 answer

After initWithCoder: is called in the cell, the cell is created and has its own properties. But the relationships in XIB (IBOutlets) in the cell are not yet complete. Therefore, when you try to use mainLabel , it is a nil reference.

Instead, move your style code to the awakeFromNib method. This method is called after the cell is created and fully configured after unpacking the XIB.

+12
source

All Articles