Add subview from a xib or another scene with storyboard

守給你的承諾、 提交于 2019-12-17 15:27:53

问题


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 approaches..

  1. Just grab an UI object from right-bottom corner window in the xcode, and then put it onto any space area of storyboard. But I can't drop the UI object like the way with xib.
  2. Add a new UIViewController. Add a view into the UIViewController. In the main ViewController.m, I get the new UIViewController instance in the viewDidLoad, and then [self.view addSubview:newUIViewController.view]. But I can't see the added view.
  3. I created a new xib file. And add a view into it. I also try to get the instance in the main ViewController. And addSubview with the xib's view. But it also failed.

Is there a correct way or any working solution to do so?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/8754157/add-subview-from-a-xib-or-another-scene-with-storyboard

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!