How to load a NIB inside of a view in another NIB?

浪子不回头ぞ 提交于 2019-12-31 21:22:31

问题


I have two NIB's

ParentViewController.xib
ChildViewController.xib

ParentViewController.xib contains a UIView and a UIViewController. ChildViewController.xib contains a UIButton

I want ChildViewController.xib to load in the ParentViewController.xib's UIView

I have done the following:

  1. Created @property for UIView in ParentViewController
  2. Connected File's Owner to UIView in ParentViewController
  3. Set UIViewController in ParentViewController's NIB Name property to ChildViewController in Interface Builder
  4. Set ChildViewController view property to UIView in ParentViewController

I was hoping this would load ChildViewController into my UIView in ParentViewController but no luck.

I did get the following warning, which could be the culprit:

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

I also have added additional code in ParentViewController's viewDidLoad():

- (void)viewDidLoad {
    [super viewDidLoad];
    ChildViewController *childViewController = [[ChildViewController alloc]initWithNibName:@"ChildViewController" bundle:nil]; 
    childViewController.view = self.myView; 
}

Any thoughts on why ChildViewController does not load in the UIView of ParentViewController?


回答1:


Try this

[self.myview addSubview: childViewController.view];

instead of

childViewController.view = self.myView; 



回答2:


The alternative is to build the "embedded" view (!) in a Nib, say ChildView.xib, then instantiate it in the ParentViewController.xib (change the class in the Identity inspector). There is no need to programmatically [self.view addSubview:embeddedView] in the parent view controller's -viewDidLoad method.

I wrote up how we embed custom-view Nibs inside other Nibs in a longish blog post. The crux is overriding -awakeAfterUsingCoder: in the ChildView class, replacing the object loaded from the "parent" Nib with the one loaded from the "child" Nib.

Note that our custom controls subclass UIView, not UIViewController (see Apple's docs on Custom view controllers: "You should not use multiple custom view controllers to manage different portions of the same view hierarchy.")



来源:https://stackoverflow.com/questions/2589582/how-to-load-a-nib-inside-of-a-view-in-another-nib

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!