首页 > 解决方案 > 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)

}

标签: swiftuicontainerview

解决方案


您还可以创建 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)

这将为您将来节省大量时间。


推荐阅读