I have a subclass \"s\" of UIView. I want to put some buttons and labels on s. How do I associate my UIView subclass with a nib file?
In my case, I didn't want my view controller to have any knowledge of the IBOutlets from my view's .xib. I wanted my view subclass to own the IBOutlets. Unfortunately UIView doesn't have an initWithNibName:
method, so I just created my own category.
Here's what I did:
initWithNibName:
to instantiate your view.And here's the category I created:
- (instancetype)initWithNibName:(NSString *)nibName
{
NSArray *arrayOfViews = [[NSBundle mainBundle] loadNibNamed:nibName owner:self options:nil];
if (arrayOfViews.count < 1) {
return nil;
}
self = arrayOfViews[0];
return self;
}
Inspired by this post.
Note though, that so far the frame will adjust automatically, so unlike the code in the post, I haven't yet had to explicitly set the frame.
Also, unlike the post's code, I needed to set owner:self
so the IBOutlets would be wired up correctly.
You should be able the drag buttons in. To get at the nib from code, use -[NSBundle loadNibNamed:owner:options:]
. Your view should be the first object in the returned array.