Razor Storm
Razor Storm

Reputation: 12336

How to init a UIView subclass when sharing a nib with another UIView

I have 2 UIViews that both use the same nib:

PictureCell and LabelCell that both inherit from ParentCell. Both of these use the nib picturecell.xib because their layouts are very similar.

PictureCell and LabelCell both override a method called setImage from ParentCell.

Currently picturecell.xib's owner is set to PictureCell.

I instantiate the PictureCell by doing [[NSBundle mainBundle] loadNibNamed:@"picturecell" owner:self options:nil][0];

How would I instantiate LabelCell?

Upvotes: 0

Views: 203

Answers (1)

rdelmar
rdelmar

Reputation: 104082

I would make separate xibs for each cell, and use registerNib:forIdentifier: instead of loading them the way you were. You can copy and paste the cell to the new xib, so you don't have to remake it.

After Edit:

I did find one way that works to share a common UI made in a xib between two cell subclasses. Instead of making a xib that's a cell, make one that is a UIView. Add all your common subviews to it, and make the file's owner the base cell class so you can hook up any outlets you've created in that class. In the base cell's init method, you can add this view as a subview of the contentView ("content" is a property created in the .h of the base cell).

@implementation RDBaseCell

-(instancetype) initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {

        _content = [[NSBundle mainBundle] loadNibNamed:@"CellContent" owner:self options:nil][0];
        [self.contentView addSubview:_content];
    }
    return self;
}

-(void)layoutSubviews {
    [super layoutSubviews];
    self.content.frame = self.contentView.bounds;
}

In the table view controller, register the class for both of your subclasses. In the init method for the subclasses, you can add any custom views that are specific for that subclass.

Upvotes: 2

Related Questions