Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to properly Init a custom UITableviewCell?

I am using the following 2 methods to return a custom cell:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {      NSString *key = [self keyForIndexPath:indexPath];     UITableViewCell *cell;      if ([key isEqualToString:DoneButtonCellKey]) {         cell = [self [self doneButtonCellForIndexPath:indexPath];         return cell;     } else {         //code to return default cell...     } }  

Then:

- (DoneButtonCell *)doneButtonCellForIndexPath: (NSIndexPath *)indexPath {      DoneButtonCell *cell = [self.tableView dequeueReusableCellWithIdentifier:DoneButtonCellIdentifier forIndexPath:indexPath];     return cell;  } 

What is the correct init method to use with the cell here so I can change some properties of the cell when it is initialized?

EDIT: I found the problem, as the init/awakeFromNib methods were not being called for me. I tracked down the error and it was that I had not changed the "Custom Class" from UITableViewCell to my custom class. Now awakeFromNib AND initWithCoder work as described below.

like image 493
Michael Campsall Avatar asked Dec 22 '13 01:12

Michael Campsall


2 Answers

You can do your changes inside the DoneButtonCell's class, either in the

- (void)awakeFromNib {  .. essential to call super ..  super.awakeFromNib()  //Changes done directly here, we have an object } 

Or the initWithCoder: method:

-(id)initWithCoder:(NSCoder*)aDecoder {    self = [super initWithCoder:aDecoder];     if(self)    {      //Changes here after init'ing self    }     return self; } 
like image 150
Mostafa Berg Avatar answered Sep 19 '22 05:09

Mostafa Berg


If you're using Swift, remember the easy way to ensure a view is initialized when it is created is to use the didSet method. For example, to make a UIImageView into a round shape you could add code like this:

@IBOutlet weak var profileImageView: UIImageView! {     didSet {         // Make the profile icon circle.         profileImageView.layer.cornerRadius = self.profileImageView.frame.size.width / 2         profileImageView.clipsToBounds = true     } } 
like image 26
TALE Avatar answered Sep 20 '22 05:09

TALE