gpt4 book ai didi

swift - 如何以编程方式在 containerView 中添加 ViewController?

转载 作者:行者123 更新时间:2023-11-28 12:37:25 24 4
gpt4 key购买 nike

如果通过界面生成器使用 socket ,我知道如何将 ViewController 添加到容器中。您只需将导出从容器拖到 ViewController 和 boom,一切就绪。但是当谈到以编程方式进行时,我在网上找不到任何答案?谁能给我一个示例代码?提前致谢。

假设我有 2 个 View Controller 和 1 个容器 View 。第一个 Controller 是父 Controller ,里面是容器 View ,容器 View 里面是第二个 View Controller 。

最佳答案

您需要先为父 View 和容器 View 添加约束,然后您还需要为您的容器 Controller 添加约束。最后,您应该在设置所有约束的最后添加 didMoveToParent。

例子如下,你可以在你的情况下做类似的事情。

 NSLayoutConstraint.activateConstraints([
containerView.leadingAnchor.constraintEqualToAnchor(view.leadingAnchor, constant: 10),
containerView.trailingAnchor.constraintEqualToAnchor(view.trailingAnchor, constant: -10),
containerView.topAnchor.constraintEqualToAnchor(view.topAnchor, constant: 10),
containerView.bottomAnchor.constraintEqualToAnchor(view.bottomAnchor, constant: -10),
])
NSLayoutConstraint.activateConstraints([
controller.view.leadingAnchor.constraintEqualToAnchor(containerView.leadingAnchor),
controller.view.trailingAnchor.constraintEqualToAnchor(containerView.trailingAnchor),
controller.view.topAnchor.constraintEqualToAnchor(containerView.topAnchor),
controller.view.bottomAnchor.constraintEqualToAnchor(containerView.bottomAnchor)
])
controller.didMoveToParentViewController(self)

或者你也可以引用这个:https://codedump.io/share/jVuaGlB85VtK/1/how-to-add-a-container-view-programmatically

关于swift - 如何以编程方式在 containerView 中添加 ViewController?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40458381/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com