Interface Builder: How to load view from nib file

前端 未结 4 1890
日久生厌
日久生厌 2021-02-10 19:20

I have a MyCustomView subclassed from NSView designed in a .xib.

I would like to insert this view into some of my other xib\'s round my application. How should

4条回答
  •  醉酒成梦
    2021-02-10 19:41

    I'd advise just doing it programmatically:

    1. Add a View to your main xib/storyboard and set the custom class to your custom view's class
    2. In your xib for your custom view, set the File's Owner class to your custom view's class
    3. Hook up any IBOutlets, etc. as needed
    4. Make a __strong property/ivar for holding a reference to the top level NSView of the xib
    5. Implement initFromFrame in your custom view's class roughly as follows:
    @interface CustomView ()
    {
        __strong NSView *nibView;
    }
    @end
    
    @implementation CustomView
    
    - (id)initWithFrame:(NSRect)frame
    {
        self = [super initWithFrame:frame];
        if (self) {
            NSArray *nibObjects;
            [[NSBundle mainBundle] loadNibNamed:@"CustomView" owner:self topLevelObjects:&nibObjects];
            nibView = nibObjects[1];
            [self addSubview:nibView];
        }
        return self;
    }
    

    The IBOutlet are connected up immediately after the loadNibNamed call, so you can do further initialization from there.

    Another option is to do things purely programmatically: 1. In your custom xib, set the root View's class to your custom class 2. Implement awakeFromNib in your custom class to perform initialization 3. Call loadNibNamed: on your custom xib and programmatically add it to the user interface without interface builder.

提交回复
热议问题