在滚动视图中切换具有不同高度的容器或视图

switch Container or View with different height within a scrollview

我试图通过单击按钮在滚动视图中放置具有不同高度的不同视图。我画了一个问题的图像:

如果您单击按钮 1 (btn1),那么我们将加载视图 1。如果您单击按钮 2,那么我们将加载视图 2。

按钮上方和显示视图下方有小部件。因此,显示视图需要以某种方式具有动态高度,不会影响滚动视图内的其他元素。我尝试了 container_views 但无法连接不同高度的视图控制器。

更新:(这里是另一个例子)

这就是我解决这个问题的方法,你的 UIScrollView 里面的一个 views 就是我所说的 containerView,我里面有 containerView 的出口例如我的 ViewController。这是我的层次结构在测试应用程序中的样子:

如您所见,我目前在 containerView 中有一个子视图,它定义了高度,BottomView - 橙色的垂直间距约束定义为 containerView .

当用户点击替换视图(在我的示例中为 replaceView(_) 方法)时,您只需首先从 containerView 中删除所有子视图,然后添加新视图,因为我们使用自动布局橙色无论big/small 容器视图如何...

,视图将始终位于容器视图下方
@IBAction func replaceView(_ sender: UIButton) {
    //remove all subviews from container view to be replaced
    for subview in containerView.subviews {
        subview.removeFromSuperview()
    }

    let greenView = UIView()
    greenView.translatesAutoresizingMaskIntoConstraints = false
    containerView.addSubview(greenView)

    NSLayoutConstraint.activate([
        greenView.leadingAnchor.constraint(equalTo: containerView.leadingAnchor),
        greenView.trailingAnchor.constraint(equalTo: containerView.trailingAnchor),
        greenView.topAnchor.constraint(equalTo: containerView.topAnchor),
        greenView.bottomAnchor.constraint(equalTo: containerView.bottomAnchor),
        greenView.heightAnchor.constraint(equalToConstant: 50)
        ])

    greenView.backgroundColor = .green
}

如果您有一个视图要添加到另一个 Storyboard View Controller 中,您可以像这样添加它:

我假设你的 Storyboard 被称为 Main 并且我添加的视图控制器的 Storyboard ID 是 GreenStoryboardID

    @IBAction func replaceView(_ sender: UIButton) {
    //remove all subviews from container view to be replaced
    for subview in containerView.subviews {
        subview.removeFromSuperview()
    }

    let storyboard = UIStoryboard(name: "Main", bundle:nil)

    let greenViewController = storyboard.instantiateViewController(withIdentifier: "GreenStoryboardID")
    guard let greenView = greenViewController.view else { fatalError() }
    //add view properly so it is uses UIViewController contaniment methods
    addChildViewController(greenViewController)
    containerView.addSubview(greenView)
    greenViewController.didMove(toParentViewController: self)

    greenView.translatesAutoresizingMaskIntoConstraints = false

    NSLayoutConstraint.activate([
        greenView.leadingAnchor.constraint(equalTo: containerView.leadingAnchor),
        greenView.trailingAnchor.constraint(equalTo: containerView.trailingAnchor),
        greenView.topAnchor.constraint(equalTo: containerView.topAnchor),
        greenView.bottomAnchor.constraint(equalTo: containerView.bottomAnchor),
        greenView.heightAnchor.constraint(equalToConstant: 50)
        ])
}

如何正确调整视图控制器的大小取决于您,这里我只是将其高度设置为 50,但是您可以在 UIViewController 子类中有一个方法,例如,它能够让你知道视图有多大才能将所有内容放入容器视图