Add subview from a xib or another scene with storyboard

前端 未结 2 1108
清歌不尽
清歌不尽 2020-12-04 17:09

I\'m new to iOS and Xcode. I can\'t figure out how to design a separated view and make it be added into the main UIViewController using storyboard.

I did different a

相关标签:
2条回答
  • 2020-12-04 17:48

    I figured out a way to do it. Described as following:

    1. Create a .xib file. For example: MyView.xib
    2. Create a objective-c class. For example: MyViewClass.h and MyViewClass.m
    3. Set the .xib File's Owner to the class.
    4. Add a UIView element on the storyboard and set the custom class to the objective-c class name (MyViewClass).
    5. The key-point is to override the initWithCoder method in the object-c class.

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

    The idea is the custom class is loaded by the storyboard and initWithCode will be called. The index 0 is the root view in the .xib interface builder.

    It's kind of tricky but it works.

    0 讨论(0)
  • 2020-12-04 17:51

    In storyboard, drag and drop a view controller. The view controller come with a main view. Select that main view by clicking outside of the added view controller and then clicking in the center of it. Now, just drag a uiview or whatever into that main view just like you did with IB.

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