Tom
Tom

Reputation: 4033

Remove subview from another ViewController

I added a PageViewController to a normal view controller as a subview in viewDidAppear() of my HomeViewController like this:

if showTutorial == false {
        addChild(controller)
        controller.view.frame = view.frame
        view.addSubview(controller.view)
        controller.didMove(toParent: self)
}

It works, but I can't figure out how to remove it again - the PageViewController contains a button which navigates through its pages. Reaching a certain page, I want to remove the PageViewController from the HomeViewController again, by clicking the button inside of the PageViewController.

How can I do so?

Button inside of PageViewController:

@objc func buttonAction(sender: UIButton!) {
    if currentTutorialPage != 4 {
        currentTutorialPage += 1
        self.setViewControllers([self.viewControllerList[currentTutorialPage]], direction: .forward, animated: false, completion: nil)
        view.bringSubviewToFront(nextButton)
        view.bringSubviewToFront(prevButton)
    } else {
        tutorialSeen = true
        defaults.set(tutorialSeen, forKey: "tutorialSeen")
    }
}

Upvotes: 0

Views: 923

Answers (3)

Shehata Gamal
Shehata Gamal

Reputation: 100503

You can try

self.view.removeFromSuperview()

For completeness sake you can use this extension

@nonobjc extension UIViewController {
    func add(_ child: UIViewController, frame: CGRect? = nil) {
        addChild(child)
        if let frame = frame {
          child.view.frame = frame
        }
        view.addSubview(child.view)
        child.didMove(toParent: self)
    }
    func remove() {
        willMove(toParent: nil)
        view.removeFromSuperview()
        removeFromParent() 
    }
}

Then

@objc func buttonAction(sender: UIButton!) {
    if currentTutorialPage != 4 {
        currentTutorialPage += 1
        self.setViewControllers([self.viewControllerList[currentTutorialPage]], direction: .forward, animated: false, completion: nil)
        view.bringSubviewToFront(nextButton)
        view.bringSubviewToFront(prevButton)
    } else {
        tutorialSeen = true
        defaults.set(tutorialSeen, forKey: "tutorialSeen")
        self.remove()
    }
}

Upvotes: 6

Rob
Rob

Reputation: 437552

To remove a child view controller (including its view), you should:

willMove(toParent: nil)
view.removeFromSuperview()
removeFromParent()

Upvotes: 2

you can remove text/views/alerts/etc from superview using

removeFromSuperview()

example:

let loaderText = "text"

loaderText?.removeFromSuperview()

for views is just the same

let container: UIView = {
        let container = UIView(frame: CGRect.zero)
        container.backgroundColor = UIColor.black.withAlphaComponent(0.5)
        container.translatesAutoresizingMaskIntoConstraints = false
        return container
    }()

used like this

container.removeFromSuperview()

Upvotes: 1

Related Questions