When using registerNib: forCellReuseIdentifier, how do I set the UITableViewCell iVars?

I am loading custom subclasses of UITableViewCell from nib.

In my viewDidLoad view viewDidLoad , registerNib:forCellReuseIdentifier . My cellForRowAtIndexPath controller uses the dequeueReusableCellWithIdentifier method to load the cell, but I never select / initialize the cell.

ViewController:

 - (void)viewDidLoad { [super viewDidLoad]; [self.tV registerNib:[UINib nibWithNibName:@"VersatileIntTFCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:kTFInt]; self.tV.delegate=self; self.tV.dataSource=self; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"Int TextField"; VersatileIntTFCell *cell = (VersatileIntTFCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier]; return cell; } 

The view of the table looks great and the cells are displayed in order.

Now I'm starting to subclass UITableViewCell . There are some iVars @property in my subclasses (they are not IBOutlets ). I would like to initialize them in the init method of a subclass of UITableViewCell , but this seems to never be called. I can run them in viewController cellForRowAtIndexPath , but I want to avoid this. I want to do this in a subclass of UITableViewCell . Is it possible? If so, how / where / when?

+4
source share
3 answers

Override the awakeFromNib method and put your code there, not in init.

From the docs:

The nib-load infrastructure sends an awakeFromNib message to each object recreated from the nib archive, but only after all objects in the archive are loaded and initialized. When an object receives an awakeFromNib message, it is guaranteed that it has all the actions already installed. You should name the awakeFromNib super implementation to provide the parent classes with the ability to perform any required initialization.

+10
source

If you want to initialize any UIView after loading it from the tip, you must override initWithCoder . awakeFromNib may also be useful. See "Overriding Methods" in the UIView link.

+3
source

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


All Articles