How to embed a custom view xib in a storyboard scene?

前端 未结 11 548
生来不讨喜
生来不讨喜 2021-01-29 21:33

I\'m relatively new in the XCode/iOS world; I\'ve done some decent sized storyboard based apps, but I didn\'t ever cut me teeth on the whole nib/xib thing. I want to use the sam

11条回答
  •  深忆病人
    2021-01-29 21:57

    You're almost there. You need to override initWithCoder in your custom class you assigned the view to.

    - (id)initWithCoder:(NSCoder *)aDecoder {
        if ((self = [super initWithCoder:aDecoder])) {
            [self addSubview:[[[NSBundle mainBundle] loadNibNamed:@"ViewYouCreated" owner:self options:nil] objectAtIndex:0]];
        }
        return self; }
    

    Once that's done the StoryBoard will know to load the xib inside that UIView.

    Here's a more detailed explanation:

    This is how your UIViewController looks like on your story board: enter image description here

    The blue space is basically a UIView that will "hold" your xib.

    This is your xib:

    enter image description here

    There's an Action connected to a button on it that will print some text.

    and this is the final result:

    enter image description here

    The difference between the first clickMe and the second is that the first was added to the UIViewController using the StoryBoard. The second was added using code.

提交回复
热议问题