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

前端 未结 2 2087
感动是毒
感动是毒 2020-12-13 10:46

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?

相关标签:
2条回答
  • 2020-12-13 10:57

    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.

    0 讨论(0)
  • 2020-12-13 11:12
    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.

    0 讨论(0)
提交回复
热议问题