6

I'm trying to use one XIB file for multiple types of custom UITableViewCell subclasses (same IBOutlets - same look - different methods and logic).

How can I do that?

Niko
  • 3,412
  • 26
  • 35
YogevSitton
  • 10,068
  • 11
  • 62
  • 95

1 Answers1

3

Strictly speaking, the framework doesn't enforce a strict binding from an xib to its file owner. You can use the following code to load a nib:

NSArray *nibContents = [[NSBundle mainBundle] loadNibNamed:@"EXCustomCell" owner:nil options:nil];
EXFirstCustomCell *firstCell = (EXFirstCustomCell*)[nibContents objectAtIndex:0];
firstCell.firstView = [firstCell.contentView viewWithTag:VIEW_TAG];
firstCell.button = [firstCell.contentView viewWithTag:BUTTON_TAG];

Based on your business logic, you can cast the result of [nibContents objectAtIndex:0]; to suit your custom UITableViewCell class.

Edit #1:

Typecasting is generally a bad idea, since the firstCell will still be kind of class UITableViewCell. A good idea would be to create your own constructor, pass the nibContents as an argument and do your view assignments there.

Edit #2

I did a bit of experimentation and here is how I got this to work:

  1. Create an independent xib view and design your cell there. It has to be a view. What you are doing here is you are defining how the contentView is going to be.

  2. Load all the views from the xib.NSArray *nibContents = [[NSBundle mainBundle] loadNibNamed:@"EXCommonContentView" owner:nil options:nil];

  3. Create a constructor of your custom cell like so:

    -initWithNibContents:(NSArray*)nibContents {
        self = [super init]
        if(self) {
           self.contentView = [nibContents objectAtIndex:0];
           self.button = [self.contentView viewWithTag:BUTTON_TAG];
           self.view = [self.contentView viewWithTag:VIEW_TAG];
        }
     }
    
avismara
  • 5,141
  • 2
  • 32
  • 56