ios - 将两个 ViewController 容器约束在一起以填满屏幕
问题描述
我想在父视图中有两个视图。一个视图应该是其内容的确切大小,然后第二个视图填充剩余的空间。
我在 iOS 故事板中有以下设置:
我的主 ViewController 有两个 ViewController 容器,一个在另一个之上。
底部 ViewController 旨在具有由其内容确定的静态高度。在这种情况下,它有一个带有顶部、底部和尾随约束的按钮。因此,如果您知道按钮的高度,您应该能够确定底部 ViewController 的高度。
顶部 ViewController 旨在是可变的 - 它有一个按钮被限制在其父视图的中间中心。无论父视图的高度或宽度如何,内部按钮都将始终居中。
在主 ViewController 中,顶视图控制器被约束到主视图的顶部和侧面,而底视图控制器被约束到主视图的底部和侧面。然后,顶视图的底部和底视图的顶部相互约束。这会中断,因为 iOS 会尝试在底部视图之前确定主视图的大小(或类似的东西)。
如何让底部视图等于其内容的高度,并让顶部视图填充剩余的任何空间?
解决方案
您不能仅使用 Storyboard来执行此操作……您需要添加一些代码。
首先,在 Storyboard / Interface Builder 中:
- 约束底部容器以查看(安全区域)前导/尾随/底部
- 给它一个高度约束——这个值在这一点上并不重要,只是为了让你看到大致的布局
- 给出高度约束
Priority: Low (250)
。这将允许它根据其嵌入视图的自动布局大小来增长/缩小。 - 约束顶部容器查看(安全区域)顶部/前导/尾随
- 将顶部容器的底部约束到底部容器的顶部
当您添加容器视图时,IB 会自动为您提供“默认”视图控制器,并设置为容器的大小。使用Attributes and Size Inspector 窗格将“Simulated Metrics”和 Size 更改为Freeform
。这允许您以您想要的大小处理“子视图控制器”。
这是它的外观示例:
当在 中嵌入视图控制器时UIContainerView
,会自动创建一个“嵌入转场”,您可以在prepare(for segue: ...)
. 使用它来获取对视图的引用,以便您可以修改它们的约束。
因此,您的viewDidLoad()
func 将包含以下内容:
// 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
推荐阅读
- attributes - Terraform - 如何使用导出的属性?
- html - 为什么这个文本的容器比它应该的宽得多?
- slack - 通过 Slack 斜杠命令提供文件
- java - 当我尝试运行 react native android 命令时出错。请帮助我实际上尝试了很多建议的人我仍然无法运行应用程序
- python - 在python列表中的每个元素之后删除n个元素
- tailwind-css - nx:在库中使用 @tailwind 关键字
- html - 我可以在网页中每个字母有相等的空间吗?
- c - 为什么 C 编程中需要 fortran 包装器?
- reactjs - 如何在 react 和 axios 中对所有请求进行分组?
- react-native - “找不到 com.android.tools.build: gradle: 4.2.2。”