I have a UIView that I want to use in several View Controllers so I created the view (.h/.m) and a nib file for it. In Storyboard view is added as subview to view controller but is not loading the layout as defined in nib.
Is it possible to load the nib for a UIView used within a view controller in a Storyboard?
If you ask about seeing your .xib content in Interface Builder when editing Storyboard, it's not possible. But if you need to load it in runtime, it's possible.
@property (strong, nonatomic) IBOutlet UIView* view;
and connect your View container from Interface Builder to this field (Ctrl + Click on View and drag connection to above view
property in .h
- (void)awakeFromNib {
NSString* nibName = @"Place here your Nib name without extension";
if ([[NSBundle mainBundle] loadNibNamed:nibName owner:self options:nil]) {
[self.view setFrame:[self bounds]];
[self addSubview:self.view];
}
}
That's all. Move View to Storyboard scene, change Custom Class to your FooView, import .h in View Controller code and use IBOutlets as you want.
Have happy coding
EDIT
I want to notice that according awakeFromNib
documentation we should avoid such code in awakeFromNib
.
It is recommended that you maintain a one-to-one correspondence between your File’s Owner objects and their associated nib files. Loading two nib files with the same File’s Owner object causes that object’s awakeFromNib method being called twice, which could cause some data structures to be reinitialized in undesired ways. It is also recommended that you avoid loading other nib files from your awakeFromNib method implementation.