gpt4 book ai didi

objective-c - 自动布局约束和 subview Controller

转载 作者:太空狗 更新时间:2023-10-30 03:41:34 25 4
gpt4 key购买 nike

我有两个 View Controller ,父 View Controller 和 subview Controller 。

所以在 viewDidLoad 方法中,我执行以下操作:

ChildViewController* childViewController = [[ChildViewController alloc] init];

[self addChildViewController:childViewController];

// ChildViewController sets his own constraints in viewDidLoad
[self.view addSubview:childViewController.view];

[childViewController didMoveToParentViewController:self];

//
// setup constraints to expand childViewController.view to
// fill the size of parent view controller
//

所以基本上发生的是 updateViewConstraints 在父 Controller 约束应用之前在 ChildViewController 上调用,所以实际上 self.view.frame == CGRectZero,与我在 ChildViewController 的自定义 loadView 方法中指定。

translatesAutoresizingMaskIntoConstraints 所有 View 都设置为 NO

在这种情况下设置约束的正确方法是什么,以便 ChildViewController 在父级之后更新他的约束?

两个 Controller 的当前日志非常令人沮丧,我不明白如何在 viewWillLayoutSubviews 之前调用 updateViewConstraints:

App[47933:c07] ChildViewController::updateViewConstraints. RECT: {{0, 0}, {0, 0}}
App[47933:c07] ParentViewController::updateViewConstraints
App[47933:c07] ChildViewController:viewWillLayoutSubviews. RECT: {{0, 0}, {984, 454}}
App[47933:c07] ChildViewController:viewDidLayoutSubviews. RECT: {{0, 0}, {984, 454}}

最佳答案

您可以在调用 addSubview: 后立即添加约束,不要忘记将 translatesAutoresizingMaskIntoConstraints 设置为 false

这是添加和隐藏带有约束的 subview Controller 的代码片段(受 apple guide 启发)

显示

private func display(contentController content : UIViewController)
{
self.addChildViewController(content)
content.view.translatesAutoresizingMaskIntoConstraints = false
self.containerView.addSubview(content.view)
content.didMove(toParentViewController: self)

containerView.addConstraints([
NSLayoutConstraint(item: content.view, attribute: .top, relatedBy: .equal, toItem: containerView, attribute: .top, multiplier: 1, constant: 0),
NSLayoutConstraint(item: content.view, attribute: .bottom, relatedBy: .equal, toItem: containerView, attribute: .bottom, multiplier: 1, constant: 0),
NSLayoutConstraint(item: content.view, attribute: .leading, relatedBy: .equal, toItem: containerView, attribute: .leading, multiplier: 1, constant: 0),
NSLayoutConstraint(item: content.view, attribute: .trailing, relatedBy: .equal, toItem: containerView, attribute: .trailing, multiplier: 1, constant: 0)
])
}

隐藏

private func hide(contentController content : UIViewController)
{
content.willMove(toParentViewController: nil)
content.view.removeFromSuperview()
content.removeFromParentViewController()
}

关于objective-c - 自动布局约束和 subview Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17928768/

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