Search code examples
swiftuiviewuiviewcontrollerswift5viewwillappear

Reload a View after Closing its subView


I have a UIViewController named A, Im adding a another controller to the A controller like this

  self.AView = (self.storyboard!.instantiateViewController(withIdentifier: "BView") as? BViewController)!

  self.addChild(self.BView)

  self.BView.view.frame = CGRect(x: 0, y: self.view.frame.height - 450, width: self.view.frame.width , height: 450)
  self.view.addSubview((self.BView.view)!)
  self.view.bringSubviewToFront(self.BView.view)

And I am closing this by using the function below

func closeCurrentView(){

   self.view.removeFromSuperview()
}

After closing this I need to reload My Aview

I have added this in My Aview but not getting called after Closing the BView

override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(true)
}

Solution

  • viewWillAppear method is called only when the view will enter in the view hierarchy, in this case before BView is removed AView is already in the view hierarchy even if not visible (so AViewController.viewWillAppear is not called when BView is removed). You have two options:

    1. Pass a reference of AViewController to BViewController (during initialization or later) so you can do this in BViewController class:
    func closeView(){
       self.view.removeFromSuperview()
       self.AViewController.view.layoutIfNeeded() // or do something else to update AView
    }
    
    1. Remove BView in AViewController class:
    func closeBView(){
       self.BViewController.view.removeFromSuperview()
       self.view.layoutIfNeeded() // or do something else to update AView
    }