gpt4 book ai didi

ios - addChildViewController 和 subview 的自动布局

转载 作者:行者123 更新时间:2023-11-30 13:59:45 24 4
gpt4 key购买 nike

我在使用 addChildViewController 实现顶部栏(如导航 Controller 栏,但自定义)时遇到问题。我在 .xib 文件中创建了这个栏,并添加了具有正确自动布局约束的按钮和图像。

我不知道在 Controller 的哪种方法中添加此栏。我的 Controller 在我想要标题所在的空间中有一个空 View 。

    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 框架中(我想要添加 subview 的空 View ),那么这还不是正确的。如果我在 viewDidLayoutSubviews 中执行此操作,它会被调用多次。

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

最佳答案

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))

关于ios - addChildViewController 和 subview 的自动布局,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33137259/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com