简体   繁体   English

使用故事板从xib或其他场景添加子视图

[英]Add subview from a xib or another scene with storyboard

I'm new to iOS and Xcode. 我是iOS和Xcode的新手。 I can't figure out how to design a separated view and make it be added into the main UIViewController using storyboard. 我无法弄清楚如何设计一个单独的视图,并使用storyboard将其添加到主UIViewController中。

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. 只需从xcode中的右下角窗口抓取一个UI对象,然后将其放在故事板的任何空间区域。 But I can't drop the UI object like the way with xib. 但我不能像使用xib那样删除UI对象。
  2. Add a new UIViewController. 添加一个新的UIViewController。 Add a view into the UIViewController . 将视图添加到UIViewController In the main ViewController.m, I get the new UIViewController instance in the viewDidLoad, and then [self.view addSubview:newUIViewController.view] . 在主ViewController.m中,我在viewDidLoad中获取新的UIViewController实例,然后是[self.view addSubview:newUIViewController.view] But I can't see the added view. 但是我看不到添加的视图。
  3. I created a new xib file. 我创建了一个新的xib文件。 And add a view into it. 并添加一个视图。 I also try to get the instance in the main ViewController . 我还尝试在主ViewController获取实例。 And addSubview with the xib's view. addSubview与厦门国际银行的观点。 But it also failed. 但它也失败了。

Is there a correct way or any working solution to do so? 是否有正确的方法或任何可行的解决方案?

I figured out a way to do it. 我想出了办法。 Described as following: 描述如下:

  1. Create a .xib file. 创建.xib文件。 For example: MyView.xib 例如:MyView.xib
  2. Create a objective-c class. 创建一个objective-c类。 For example: MyViewClass.h and MyViewClass.m 例如:MyViewClass.h和MyViewClass.m
  3. Set the .xib File's Owner to the class. 将.xib文件的所有者设置为该类。
  4. Add a UIView element on the storyboard and set the custom class to the objective-c class name (MyViewClass). 在故事板上添加UIView元素,并将自定义类设置为objective-c类名(MyViewClass)。
  5. The key-point is to override the initWithCoder method in the object-c class. 关键点是覆盖object-c类中的initWithCoder方法。

     - (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. 想法是故事板加载自定义类并调用initWithCode。 The index 0 is the root view in the .xib interface builder. 索引0是.xib接口构建器中的根视图。

It's kind of tricky but it works. 这有点棘手,但它确实有效。

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. 现在,只需将uiview或其他内容拖动到主视图中,就像使用IB一样。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM