ios - 如何通过 Storyboard 中的组件自行调整容器 View 大小

标签 ios swift

我已将容器 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”中的标签将有可变数量的行:

enter image description here

我们希望容器 View 自动更改其高度,以便所有文本都适合。但是,如果我们添加 10 行文本,“默认”结果将是:

enter image description here

因此,我们为容器 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 的低优先级高度常量,导致:

enter image description here

这是两个 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/

相关文章:

ios - 无法弄清楚如何在 Swift 中使用闭包

ios - 如何重叠 stackView 中的 subview ?

ios - 在 Swift 中子类化 Parse 的 PFUser

ios - 为什么使用 'lazy var' 创建实例时会出现编译器错误?

ios - 为什么我的按钮在横向模式下不显示?

ios - 在 2 个 View Controller 中使用相同的 UIWebview 作为 subview

objective-c - 如何在不更改 Xcode 项目的情况下 #ifdef 环境变量?

ios - 如何将核心数据用于主要应用程序和单元测试?

ios - 使用 "PhoneGap Build"提交到 App Store 构建的 PhoneGap 应用程序

swift - swift 中的 `.floatValue` 是什么