我想使我的代码保持模块化,因此我有一个ContainerView指向子viewController。我希望ContainerView的大小根据子控制器中视图的大小而改变在更简单的情况下,在上图中,如果我使用StackView,则如果其中一个堆栈可以让父级紫色视图调整大小视图的孩子是隐藏的,还是两者都有。
我希望容器视图(在图片中显示为灰色视图)发生相同的事情,如果所包含的堆栈视图调整大小,则父容器视图的调整大小。我对containerView确实有相等的高度限制。但是,它似乎不起作用,我不确定是否有可能。我希望它调整大小,因为它阻止了对基础视图的点击。
我相信它与这个问题相似,但有足够不同,因为我们正在谈论堆栈视图。,Child ViewController to resize containerView
是,有可能。
1-给您的UIContainerView
顶部,顶部和底部约束
2-给您的UIContainerView
一个高度约束,其中Priority: Low (250)
...将被通过代码添加的新约束“覆盖”。
3-根据需要设置子视图控制器...在这种简单情况下,将堆栈视图限制为所有4个面
4-加载子视图后,在其.translatesAutoresizingMaskIntoConstraints = false
上设置.view
,然后在容器视图的所有4个侧面添加约束
假设您已正确配置了所有约束,则容器视图的高度将由其子视图(子VC的视图)确定。
示例代码:
class AutoSizeContainerViewController: UIViewController {
@IBOutlet var theContainerView: UIView!
// so we can reference the embedded VC
var subVC: SubViewController?
// this executes before viewDidLoad()
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let vc = segue.destination as? SubViewController {
self.subVC = vc
}
}
override func viewDidLoad() {
super.viewDidLoad()
// make sure subVC was set correctly
if let vc = self.subVC {
// constrain child VC's view to container view
vc.view.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
vc.view.topAnchor.constraint(equalTo: theContainerView.topAnchor),
vc.view.leadingAnchor.constraint(equalTo: theContainerView.leadingAnchor),
vc.view.trailingAnchor.constraint(equalTo: theContainerView.trailingAnchor),
// this will keep the container view's bottom equal to the child VC's view content
theContainerView.bottomAnchor.constraint(equalTo: vc.view.bottomAnchor, constant: 0.0),
])
}
}
}