如何根据子视图控制器(UIViewController)的高度来更改容器视图(父视图)的高度?

4

想要根据推送的UIViewController更改容器视图的高度。目前我不知道如何更新容器视图的高度。


为什么不使用具有乘数和/或常量参数的高度约束?还是我漏了什么? - trndjc
我想要一个东西,使得我的容器视图可以自动使用其子视图控制器的高度(不同大小的视图控制器)。或者想要从子视图控制器触发某些东西到绿色视图控制器,以便我可以更改容器视图的高度常量。 - Himanshu jamnani
2个回答

1
在您的内容视图控制器中设置preferredContentSize,如下所示。
override func viewDidLoad() {
    super.viewDidLoad()
    preferredContentSize = CGSize(width: 400, height: 200)
}

When the child gets added to the parentViewController, the parentViewController gets notified about the prefered size. Following function gets called on the parent

func preferredContentSizeDidChange(forChildContentContainer container: UIContentContainer)

In this method you can then change the container to the prefered size of the child.
For example change the height to the prefered height of the child/content

override func preferredContentSizeDidChange(forChildContentContainer container: UIContentContainer) {
    // heightConstraint is a IBOutlet to your NSLayoutConstraint you want to adapt to height of your content
    heigtConstraint.constant = container.preferredContentSize.height
}

maybe you have to pass it through your NavigationViewController. In my example there is no NavigationViewController between the parent and the content.


1
在iOS中,UI模型通常是由父视图控制子视图的大小。例如,每个视图都有一个initWithFrame构造函数,创建视图的人(通常是父视图创建子视图)应该传递大小。这被称为“基于框架的布局”。这个系统有点“自上而下”。
然而,自动布局允许您将父视图和子视图“粘”在一起,并指定这些“粘合”约束相对于父视图的大小和位置约束的优先级。如果“粘合”(和子视图的压缩阻力)胜过父视图的约束,则父视图将根据子视图的大小重新调整大小。
使用自动布局约束对于这个问题很简单,只需要有两个自定义视图(父视图和子视图),但问题在于你的父视图和子视图之间似乎有一个UINavigationController。我不建议在这里使用这种布局的原因之一是导航栏通常应该在应用程序屏幕的顶部,并且在导航时不应该上下跳动。另一个原因是由UINavigationController决定约束子视图的方式,尝试改变它的习惯并不是我推荐的做法。
你可以尝试实现navigationController:willShowViewController:animated:委托方法,并尝试根据推送哪个子视图控制器来手动调整UINavigationController的高度。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接