Programmatically change a UITableViewCell initialized from a tip?

I load a UITableViewCell from nib using [[NSBundle mainBundle] loadNibNamed: ...]. Now I want to do some work after initialization programmatically before tableviewcell will be used in my code. Where should I put this code, since I cannot do this in the initWithCoder methods, since the label objects in the class are still zero (so they cannot set anything). When are UILabels initialized in tableviewcell (all of them are defined as IBOutlets)?

+3
source share
1 answer

You must subclass UITableViewCelland put in a method awakeFromNibto perform initialization after waking up from nib.

To make your code flexible, put this initialization code in some procedure called myInitand call it from awakeFromNiband from other places where it should be called.

After some battles, I came up with a slightly different approach for this situation. I am a subclass UITableViewCelland follow the initialization procedure as follows:

- (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 contentViewis IBOutletcontaining the contents of the cell. This allows the rest of my code to simply call this cell like any other cell. (except for one nasty throw for (MyUITableViewCell*)[tv dequeueReusableCellWithIdentifier:CellIdentifier];)

+5
source

Source: https://habr.com/ru/post/1782711/


All Articles