如何在另一个NIB文件中的视图中加载NIB文件?

12

我有两个 NIB 文件

ParentViewController.xib
ChildViewController.xib

ParentViewController.xib包含一个UIView和一个UIViewController。 ChildViewController.xib包含一个UIButton。

我想让ChildViewController.xib加载到ParentViewController.xib的UIView中

我已经完成了以下步骤:

  1. 在ParentViewController中创建了UIView的@property属性
  2. 将File's Owner连接到ParentViewController中的UIView
  3. 在Interface Builder中将ParentViewController的NIB Name属性中的UIViewController设置为ChildViewController
  4. 将ChildViewController的view属性设置为ParentViewController中的UIView

我希望这样可以将ChildViewController加载到ParentViewController的UIView中,但不幸的是没有成功。

我得到了以下警告,可能是问题所在:

'View Controller (Child View)' has both its 'NIB Name' property set and its 'view' outlet connected. This configuration is not supported.

我还在ParentViewController的viewDidLoad()方法中添加了额外的代码:

- (void)viewDidLoad {
    [super viewDidLoad];
    ChildViewController *childViewController = [[ChildViewController alloc]initWithNibName:@"ChildViewController" bundle:nil]; 
    childViewController.view = self.myView; 
}
任何想法为什么ChildViewController不能在ParentViewController的UIView中加载?
2个回答

6

试试这个

[self.myview addSubview: childViewController.view];

代替
childViewController.view = self.myView; 

5
可以使用 Interface Builder 吗? - wezzy

5
另一种方法是在 Nib 中构建“内嵌”视图,例如 ChildView.xib,然后在 ParentViewController.xib 中实例化它(在 Identity 检查器中更改类)。无需在父视图控制器的 -viewDidLoad 方法中以编程方式使用 [self.view addSubview:embeddedView]

我在一篇较长的博客文章中介绍了我们如何在其他 Nib 中嵌入自定义视图 Nib。关键是在 ChildView 类中覆盖 -awakeAfterUsingCoder:,用从“子”Nib 加载的对象替换从“父”Nib 加载的对象。

请注意,我们的自定义控件是 UIView 的子类,而不是 UIViewController(请参阅苹果有关自定义视图控制器的文档:“不应使用多个自定义视图控制器来管理同一视图层次结构的不同部分。”)


你有没有检查你提供的链接中的“容器视图控制器安排其他视图控制器的内容”部分...自从iOS5以来,你可以使用UIViewController容器选项。 - tapmonkey
2
你的博客文章链接已失效。 - expert
1
@ruslan:对我来说没问题...无论如何,这里有一个更新:http://blog.yangmeyer.de/blog/2012/07/09/an-update-on-nested-nib-loading - Yang Meyer
博客页面损坏 - androidguy

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接