MrDatabase
MrDatabase

Reputation: 44425

How do I associate a nib (.xib) file with a UIView?

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?

Upvotes: 20

Views: 25871

Answers (2)

djibouti33
djibouti33

Reputation: 12132

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:

  • In IB, click on your main UIView, and in the Identity Inspector, set the class to your subclass
  • In IB, click on File's Owner, and in the Identity Inspector, set the class to your subclass
  • Use your new category method 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.

Upvotes: 3

Colin Barrett
Colin Barrett

Reputation: 4451

  1. In Interface Builder, create a new xib with the View template.
    • Click on the view in the list of objects in the xib (you should also see "File's Owner and "First Responder").
    • Push Cmd-4 to open the Identity pane of the inspector.
    • Type your class's name into the "Class Name" field and push return.

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.

Upvotes: 28

Related Questions