使用故事板从xib或其他场景添加子视图 [英] Add subview from a xib or another scene with storyboard
问题描述
我是iOS和Xcode的新手。
我无法弄清楚如何设计一个单独的视图,并使用故事板将其添加到主UIViewController中。
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..
- 只需从xcode的右下角窗口抓取一个UI对象,然后将其放在故事板的任何空白区域。但是我不能像使用xib那样删除UI对象。
- 添加一个新的UIViewController。将视图添加到
UIViewController
中。在主ViewController.m中,我在viewDidLoad中获取新的UIViewController
实例,然后[self.view addSubview:newUIViewController.view]
。但是我看不到添加的视图。 - 我创建了一个新的xib文件。并添加一个视图。我还尝试在主
ViewController
中获取实例。并使用xib的视图addSubview
。但它也失败了。
- 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.
- Add a new UIViewController. Add a view into the
UIViewController
. In the main ViewController.m, I get the newUIViewController
instance in the viewDidLoad, and then[self.view addSubview:newUIViewController.view]
. But I can't see the added view. - I created a new xib file. And add a view into it. I also try to get the instance in the main
ViewController
. AndaddSubview
with the xib's view. 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:
- 创建.xib文件。例如:MyView.xib
- 创建一个objective-c类。例如:MyViewClass.h和MyViewClass.m
- 将.xib文件的所有者设置为类。
- 在故事板上添加UIView元素将自定义类设置为objective-c类名(MyViewClass)。
-
关键点是覆盖对象中的 initWithCoder 方法 - c class。
- Create a .xib file. For example: MyView.xib
- Create a objective-c class. For example: MyViewClass.h and MyViewClass.m
- Set the .xib File's Owner to the class.
- Add a UIView element on the storyboard and set the custom class to the objective-c class name (MyViewClass).
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;
}
这个想法是自定义类由故事板加载,并将调用initWithCode。
索引0是.xib界面构建器中的根视图。
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.
这篇关于使用故事板从xib或其他场景添加子视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!