使用故事板从 xib 或其他场景添加子视图 [英] Add subview from a xib or another scene with storyboard
本文介绍了使用故事板从 xib 或其他场景添加子视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是 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
中获取实例.和addSubview
与 xib 的视图.但它也失败了.
- 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 文件的所有者设置为类.
- 在storyboard上添加一个UIView元素,并将自定义类设置为objective-c类名(MyViewClass).
关键点是覆盖 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;
}
这个想法是自定义类由故事板加载并调用 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屋!
查看全文