仅使用情节提要无法做到这一点...您需要添加一些代码。
首先,在 Storyboard/Interface Builder 中:
- 约束底部容器以查看(安全区域)前导/尾随/底部
- 给它一个高度约束——这个值在这一点上并不重要,只是为了让你看到大致的布局
- 给出高度约束
Priority: Low (250)。这将允许它根据其嵌入视图的自动布局大小来增长/缩小。
- 约束顶部容器以查看(安全区域)顶部/前导/尾随
- 将顶部容器的底部约束到底部容器的顶部
当您添加容器视图时,IB 会自动为您提供“默认”视图控制器,并设置为容器的大小。使用 Attributes 和 Size 检查器窗格将“Simulated Metrics”和 Size 更改为 Freeform。这允许您以您想要的大小处理“子视图控制器”。
这是它的外观示例:
在UIContainerView 中嵌入视图控制器时,会自动创建“嵌入转场”,您可以在prepare(for segue: ...) 中获取对“子”视图控制器(及其视图)的引用。使用它来获取对视图的引用,以便您可以修改它们的约束。
所以您的 viewDidLoad() 函数将包含如下内容:
// a View Controller's "root" view loads with
// .translatesAutoresizingMaskIntoConstraints = true
// but we want to let auto-layout change it
topVCView.translatesAutoresizingMaskIntoConstraints = false
botVCView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
// constrain all 4 sides of top view to top container
// because the Top container view has a Priority: 1000 height constraint,
// this will "fit" the top VC's view into the auto-layout sized top container
topVCView.topAnchor.constraint(equalTo: topContainerView.topAnchor),
topVCView.bottomAnchor.constraint(equalTo: topContainerView.bottomAnchor),
topVCView.leadingAnchor.constraint(equalTo: topContainerView.leadingAnchor),
topVCView.trailingAnchor.constraint(equalTo: topContainerView.trailingAnchor),
// constrain all 4 sides of bottom view to bottom container
// because the Bottom container view has a Priority: 250 height constraint,
// the auto-layout height of the Bottom VC's view will determine the height of the bottom container
botVCView.topAnchor.constraint(equalTo: bottomContainerView.topAnchor),
botVCView.bottomAnchor.constraint(equalTo: bottomContainerView.bottomAnchor),
botVCView.leadingAnchor.constraint(equalTo: bottomContainerView.leadingAnchor),
botVCView.trailingAnchor.constraint(equalTo: bottomContainerView.trailingAnchor),
])
这是一个如何看待运行时的示例:
在 GitHub 上有另一个“自动调整大小的容器视图”示例,所以我将您的布局添加到第二个示例中。你可以在这里得到它,所以你可以检查布局、约束和代码(并运行它来查看结果):https://github.com/DonMag/AutosizeContainer