[英]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.. 我做了不同的方法..
UIViewController
. UIViewController
。 In the main ViewController.m, I get the new UIViewController
instance in the viewDidLoad, and then [self.view addSubview:newUIViewController.view]
. UIViewController
实例,然后是[self.view addSubview:newUIViewController.view]
。 But I can't see the added view. 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:
描述如下:
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.