martin petrov
martin petrov

Reputation: 123

Present view controller in a container view at collection view didSelectItemAtIndexPath swift

I am trying to present a view controller in a container view when i select a cell from a collection view. The problem is that I can't seem to understand how to present it in the container below the collection view. enter image description here

I tried:

if (indexPath.row == 0){

                // Presenting first view controller

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

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

How can I make it go to the container instead of presenting the whole view controller. Thanks in advance!

Upvotes: 3

Views: 2890

Answers (2)

Dmih
Dmih

Reputation: 616

Swift 5.0 Use this functions to add and remove child 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()
    }

adopted from here

Upvotes: 1

almas
almas

Reputation: 7187

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

Upvotes: 2

Related Questions