Reputation: 11502
I am loading a UITableViewCell from a nib using [[NSBundle mainBundle] loadNibNamed:...]. Now I want to do some post-initialization work programmatically, before the tableviewcell get used in my code. Where should I put this code, as I can't seem to do it in the initWithCoder methods, as the label objects in the class are still nil (so can't set anything). When are the UILabels in the tableviewcell initialized in the first place (they are all defined as IBOutlets)?
Upvotes: 3
Views: 3674
Reputation: 47084
You should subclass UITableViewCell
, and put an awakeFromNib
method in it to perform initializations after awaking from the nib.
To keep your code flexible, put this init code in some routine called myInit
and call that from awakeFromNib
, and from other places where it should be called.
After some struggles I've come up with a slightly different approach for this situation. I subclass UITableViewCell
and have an init routine like this:
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
[[NSBundle mainBundle] loadNibNamed:@"MyUITableViewCell" owner:self options:nil];
[self addSubview:self.contentView];
}
return self;
}
where contentView
is an IBOutlet
containing the cell content. This allows the rest of my code to just invoke this cell as any other cell. (apart from one nasty cast for (MyUITableViewCell*)[tv dequeueReusableCellWithIdentifier:CellIdentifier];
)
Upvotes: 5