在集合视图中的容器视图中显示视图控制器didSelectItemAtIndexPath swift

时间:2015-12-04 16:23:22

标签: ios swift uicollectionview uicontainerview

当我从集合视图中选择一个单元格时,我试图在容器视图中显示一个视图控制器。问题是我似乎无法理解如何在集合视图下方的容器中呈现它。 enter image description here

我试过了:

if (indexPath.row == 0){

                // Presenting first view controller

    let detailedViewController: ViewController =
          self.storyboard!.instantiateViewControllerWithIdentifier("ViewController") as! ViewController

                self.presentViewController(detailedViewController, animated: true, completion: nil)

如何让它转到容器而不是呈现整个视图控制器。 提前谢谢!

2 个答案:

答案 0 :(得分:2)

self.addChildViewController(detailedViewController)
containerView.addSubview(detailedViewController.view)

答案 1 :(得分:0)

Swift 5.0使用此功能可以添加和删除子VC:

private func add(asChildViewController viewController: UIViewController, childFrame:CGRect) {
        // Add Child View Controller
        addChild(viewController)

        // Add Child View as Subview
        view.addSubview(viewController.view)

        // Configure Child View
        viewController.view.frame = childFrame
        viewController.view.autoresizingMask = [.flexibleWidth, .flexibleHeight]

        // Notify Child View Controller
        viewController.didMove(toParent: self)

    }
    private func remove(asChildViewController viewController: UIViewController) {
        // Notify Child View Controller
        viewController.willMove(toParent: nil)

        // Remove Child View From Superview
        viewController.view.removeFromSuperview()

        // Notify Child View Controller
        viewController.removeFromParent()
    }

来自here