将两个 ViewController 容器约束在一起以填满屏幕

Constraining two ViewController containers together to fill the screen

我想在一个父视图中有两个视图。一个视图应该是其内容的确切大小,然后第二个视图填充剩下的 space。

我在 iOS 故事板中有以下设置:

我的主 ViewController 有两个 ViewController 容器,一个在另一个上面。

底部 ViewController 旨在具有静态高度,由其内容决定。在本例中,它有一个带有顶部、底部和尾部约束的按钮。因此,如果您知道按钮的高度,您应该能够确定底部的高度 ViewController。

顶部 ViewController 旨在可变 - 它有一个按钮被限制在其父视图的中间中心。无论父视图的高度或宽度如何,内部按钮将始终居中。

在主 ViewController 中,顶视图控制器被限制在主视图的顶部和侧面,而底部视图控制器被限制在主视图的底部和侧面。然后,顶视图的底部和底视图的顶部相互约束。这会中断,因为 iOS 试图在底部视图(或类似的东西)之前确定主视图的大小。

如何让底视图等于其内容的高度,并让顶视图填充任何 space 剩余的内容?

您不能仅使用 情节提要...您需要添加一些代码。

首先,在 Storyboard/Interface Builder 中:

  • 限制底部容器查看(安全区域)前导/尾随/底部
  • 给它一个高度限制——这个值在这一点上并不重要,只是让你看到大致的布局
  • 给出高度限制 Priority: Low (250)。这将允许它根据其嵌入式视图的自动布局大小增长/缩小。
  • 限制顶部容器查看(安全区域)顶部/前导/尾随
  • 将顶部容器的底部限制为底部容器的顶部

IB 在您添加容器视图时自动为您提供 "default" 视图控制器,设置为容器的大小。使用 AttributesSize Inspector 窗格将 "Simulated Metrics" 和 Size 更改为 Freeform。这使您可以根据自己的需要在 "sub View Controllers" 上工作。

这是它的外观示例:

UIContainerView 中嵌入视图控制器时,会自动创建一个 "embed segue",您可以在 "sub" 中获得对视图控制器(及其视图)的引用=14=]。使用它来获取对视图的引用,因此您可以修改它们的约束。

因此您的 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 上有另一个 "auto-sizing container view" 示例,所以我将您的布局添加到第二个示例中。你可以在这里得到它,所以你可以检查布局、约束和代码(和 运行 它以查看结果):https://github.com/DonMag/AutosizeContainer