Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove UIViewController from container view?

Tags:

ios

swift

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 ?

like image 783
Adrian Avatar asked Jul 22 '26 10:07

Adrian


1 Answers

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.

like image 78
rmaddy Avatar answered Jul 24 '26 03:07

rmaddy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!