我已将容器 View 添加到 Storyboard中的 UIViewController
,该 View 由单独的 UIViewController
管理。这个容器 View 需要有一个与之关联的高度才能正确地布置项目。但是,此容器 View 的高度是动态的,因为它包含一个 UITextView
以及其他项目。以前,当我不使用容器 View 时,自动布局会为我计算项目的高度。现在我已经将所有内容都移到了容器 View 中,这似乎是不可能的。我是否必须手动计算容器 View 的高度并将其应用于约束,或者是否有办法让自动布局处理它?</p>
最佳答案
你可以做到这一点,但你需要一些代码。
当 UIViewController
嵌入到容器 View 中时,其“ Root View ”的 .translatesAutoresizingMaskIntoConstraints
设置为 true,其框架自动设置为容器 View 。
如果您的嵌入式 VC 设置了约束以适当调整自身大小,您可以在加载时在其 Root View 上禁用 .translatesAutoresizingMaskIntoConstraints
。
举个例子,假设我们有这样的布局,“content VC”中的标签将有可变数量的行:
我们希望容器 View 自动更改其高度,以便所有文本都适合。但是,如果我们添加 10 行文本,“默认”结果将是:
因此,我们为容器 View 提供 8
的 Top/Leading/Trailing 约束(因此我们在两侧有一点填充),以及 128
的高度约束...但我们将高度约束的 Priority
更改为 250(低)
。这满足 IB,但在运行时为我们提供了高度的灵 active 。
在我们的“内容 VC”中,我们添加一个标签并将其 Top/Leading/Trailing/Bottom 全部限制为 8
(同样,只是为了一些填充),当然,行数设置到 0
。
现在,在我们的主 VC 中,我们实现 prepare(for segue...)
并在嵌入式 VC 的 Root View 上禁用 .translatesAutoresizingMaskIntoConstraints
:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
super.prepare(for: segue, sender: sender)
if let childViewController = segue.destination as? MyContentViewController {
childViewController.view.translatesAutoresizingMaskIntoConstraints = false
}
}
现在,在运行时,标签的固有高度将增加其父 View ( Root View )的高度,这将覆盖容器 View 的低优先级高度常量,导致:
这是两个 VC 的完整代码:
import UIKit
class MyContentViewController: UIViewController {
@IBOutlet var theLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// add 10 lines of text to the label
theLabel.text = (1...10).map({ "Line \($0)" }).joined(separator: "\n")
}
}
class ContainerContentViewController: UIViewController {
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
super.prepare(for: segue, sender: sender)
if let childViewController = segue.destination as? MyContentViewController {
childViewController.view.translatesAutoresizingMaskIntoConstraints = false
}
}
}
关于ios - 如何通过 Storyboard 中的组件自行调整容器 View 大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53481087/