One XIB for multiple subclasses of UITableViewCell

I am trying to use one XIB file for several types of custom subclasses of UITableViewCell (the same IBOutlets - same appearance - different methods and logic).

How can i do this?

+6
source share
1 answer

Strictly speaking, the framework does not provide strict binding from xib to its file owner. You can use the following code to load the knife:

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 make the result [nibContents objectAtIndex:0]; according to your custom UITableViewCell class.

Edit # 1:

Typing is usually a bad idea, as firstCell will still have a UITableViewCell class. It would be a good idea to create your own constructor, pass nibContents as an argument, and assign your assignments there.

Edit # 2

I was experimenting a bit, and here is how I got this to work:

  • Create an independent xib view and create your cell. This should be an opinion. What you are doing here is determining how the contentView will be.

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

  • Create your custom cell constructor as follows:

     -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]; } } 
+2
source

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


All Articles