Adrian
Adrian

Reputation: 20058

How to remove UIViewController from container view?

This is what I have done. The adding part is working, but the remove part is not:

extension UIViewController {
    func add(_ child: UIViewController, containerView: UIView) {
        addChildViewController(child)
        containerView.addSubview(child.view)
        child.didMove(toParentViewController: self)
    }

    func remove(containerView: UIView) {
        guard parent != nil else { return }

        willMove(toParentViewController: nil)
        removeFromParentViewController()
        containerView.removeFromSuperview()
    }
}

I tried to update this code which originally would add and remove child view controllers. But what I want is to add and remove from a container view.

Can someone point out what is the problem with the remove part ?

Upvotes: 2

Views: 5309

Answers (2)

rmaddy
rmaddy

Reputation: 318774

Your add and remove should both be from the same point of view. Either self should be the parent view controller in both cases or self should be the child view controller in both cases. Right now, you seem to have add with self as the parent and remove with self as the child.

Here's your extension where self is the child in both:

extension UIViewController {
    func add(_ parent: UIViewController) {
        parent.addChildViewController(self)
        parent.view.addSubview(view)
        didMove(toParentViewController: parent)
    }

    func remove() {
        guard parent != nil else { return }

        willMove(toParentViewController: nil)
        removeFromParentViewController()
        view.removeFromSuperview()
    }
}

The only piece missing is setting the child view controller's view's frame after adding it to the parent controller. Add such a line after the call to add or add a frame as a second parameter to add.

Upvotes: 8

Shehata Gamal
Shehata Gamal

Reputation: 100503

It's better to consider it from the child not the parent

func remove() {
   willMove(toParentViewController: nil)
   view.removeFromSuperview()
   removeFromParentViewController()
}

//

child.remove()

Upvotes: 2

Related Questions