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?
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:
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.
Load all the views from the xib.NSArray *nibContents = [[NSBundle mainBundle] loadNibNamed:@"EXCommonContentView" owner:nil options:nil];
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];
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With