2015-10-14 103 views
0

我无法使用addChildViewController来实现顶部栏(如导航控制器栏,但自定义)。 我在.xib文件中创建了该栏,并添加了具有适当自动布局约束的按钮和图像。addChildViewController和子视图的自动布局

我不知道我的控制器添加此栏的方法。我的控制器在我想要标题的空间中有一个空视图。

let customHeader = HeaderViewController(nibName: "HeaderViewController",bundle: nil) 
    self.addChildViewController(customHeader) 
    customHeader.view.frame = self.headerView.frame 
    self.view.addSubview(customHeader.view) 
    customHeader.didMoveToParentViewController(self) 

如果我把在headeView(这里我想补充的子视图空视图)的viewWillApear或viewDidLoad中框代码这段台词是不是正确的呢。 如果我在viewDidLayoutSubviews中做了它,它会被调用很多次。

我应该把它放在哪里?或者我可以解决布局问题?

+0

是不是有一个原因,你不想在'self.headerView'中约束'customHeader.view'的布局约束? –

+0

self.headerView只是一个白色视图,其中包含mainViewController中其余元素的约束。像0空间顶部布局,领先,trailling和底部空间。 customHeader视图已经有了他所拥有的元素的布局,就像一个图像和一些按钮一样 – misoza

+0

将'customHeader.view'至少限制在自己的前导/测试/顶部/底部可能是明智的.headerView',如果这真的是你想要它的大小/地方。 –

回答

0

您需要添加约束customHeader.view你把它添加后self.view让您的布局完全指定(你现在正在做的事情可能会奏效,但要看是否self.headerView已经是你想要的它是)。你可以做类似如下的事情:

self.view.addConstraint(NSLayoutConstraint(item: customHeader.view, attribute: .Leading, relatedBy: .Equal, toItem: self.headerView, attribute: .Leading, multiplier: 1.0, constant: 0.0)) 
self.view.addConstraint(NSLayoutConstraint(item: customHeader.view, attribute: .Trailing, relatedBy: .Equal, toItem: self.headerView, attribute: .Trailing, multiplier: 1.0, constant: 0.0)) 
self.view.addConstraint(NSLayoutConstraint(item: customHeader.view, attribute: .Top, relatedBy: .Equal, toItem: self.headerView, attribute: .Top, multiplier: 1.0, constant: 0.0)) 
self.view.addConstraint(NSLayoutConstraint(item: customHeader.view, attribute: .Bottom, relatedBy: .Equal, toItem: self.headerView, attribute: .Bottom, multiplier: 1.0, constant: 0.0))