I am trying to create a custom view, with a nib and attendant .h/.m files, and then create multiple instances of that view via IB, and use them as subviews of another view.
I do steps 5 and 6 multiple times, once for each view I want. Eventually I would connect these views to IBOutlets on the parent view class.
Obviously I am doing something wrong because I am not seeing my labels in the custom view. I suspect I need to associate the nib with the view directly, much like you do with collection/table view, but I haven't found where to do this.
What is the correct way to do this? I suppose I could add views programmatically, but then how do I handle the layout for various devices (e.g. iphone 4 vs 5)?
What I outline below appears to work
1) Create the xib and .h/.m files for your custom view.
1a) Assuming you need IBOutlets to view elements over which you want control, give the File's Owner the class name defined in your .h file in the identity inspector.
2) In .h file define a property
@property (nonatomic, retain) IBOutlet UIView *contentView;
2a) define outlets for all the subviews in your xib, to which you want programmatic access.
3) In the .m file synthesize the property and do
- (void)awakeFromNib
{
NSLog(@"awake from nib");
[[NSBundle mainBundle] loadNibNamed:@"yourNibName" owner:self options:nil];
[self addSubview:self.contentView];
}
4) Drag empty views from the palette into their container in the storyboard. Change the class of these views to the class name defined in your .h file.
When you run your app you should see the contents of the xib in your subviews.
5) You can now define outlets to your custom subview instances in the .h file of the container view, and connect them as usual in the storyboard.
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