swift - Swift,与 containerView 相关的新手问题。如何使孩子的故事板视图控制器与容器视图的大小相同
问题描述
在观看和阅读各种教程后,我一直在尝试在我的练习应用程序中正确实现一个 ContainerView。我最初尝试通过使用情节提要并将 ContainerView 拖到有问题的 ViewController 上来创建子项,然后使用随后自动创建的子 ViewController,但我需要有多个子 ViewController,但我无法弄清楚。我研究了一些程序化的方法来做到这一点,并成功地让它按照我想要的方式运行。唯一的问题是,当我在情节提要上查看子 ViewController 时,它们是全尺寸的,并且与我的 ContainerView 的大小无关。所以我必须进行一些试验和错误才能让我放置在孩子中的对象适合 ContainerView。
谁能给我一些关于如何解决这个问题的指示?我使用了下面的代码。该函数在父 ViewController 上的按钮被触摸时运行。还有其他关联的子 ViewController:child2、child3,它们根据按下的按钮运行。为了简洁起见,我没有在下面包含额外的代码。
private lazy var child1: PersonInfoChildView1Controller = {
let storyboard = UIStoryboard(name: "Main", bundle: Bundle.main)
var viewController = storyboard.instantiateViewController(withIdentifier: "Child1VC") as! PersonInfoChildView1Controller
viewController.person = self.person
addChild(viewController)
return viewController
}()
//MARK: ADD THE CHILD
private func add(asChildViewController viewController: UIViewController) {
containerView.addSubview(viewController.view)
// Configure Child View
viewController.view.frame = containerView.bounds
viewController.view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
// Notify Child View Controller
viewController.didMove(toParent: self)
}
解决方案
您还可以创建 UIView 类的扩展,仅通过一行代码将视图固定到父视图
extension UIView {
func pin(to superview: UIView){
translatesAutoresizingMaskIntoConstraints = false
topAnchor.constraint(equalTo: superview.topAnchor).isActive = true
leadingAnchor.constraint(equalTo: superview.leadingAnchor).isActive = true
trailingAnchor.constraint(equalTo: superview.trailingAnchor).isActive = true
bottomAnchor.constraint(equalTo: superview.bottomAnchor).isActive = true
}
}
使用此方法将其放在单独的 swift 文件中,您可以使容器视图与视图控制器大小相同
containerView.addSubview(viewController.view)
viewController.view.pin(containerView)
这将为您将来节省大量时间。
推荐阅读
- rows - 斜坡动力枢轴
- c# - 在 JSON.NET 中反序列化十进制值的自定义规则
- excel - 大矩阵的高级过滤器,如何获取员工的所有信息,只需输入员工编号
- python - Python:为什么使用 FFT 方法去除频率似乎并没有去除数据中的周期性?
- ios - 让我的 Firemonkey 应用程序 (Tokyo R3) 部署到我的测试设备
- c++ - 在 C++ 中在全局范围内运行代码(是否有更现代的方法)?
- reactjs - 在 React 中在哪里声明我的函数和变量
- flutter - 实现导航器时出现异常。使用不包含 Navigator 的上下文请求的 Navigator 操作
- python - python request.post的语法错误
- types - Ada:子类型转换或调用'Base