Transition to MainVC gives the empty View without subviews

95 Views Asked by At

I'm using this type of transition to UIViewcontroller:

self.navigationController?.popToViewController(MainVC(), animated: false)

And in result i want to receive the MainVC with all subviews... but i receive only empty main View without any subviews. What i did wrong?

Update: I have the transition to MainVC, but it's empty, only initial View, without all subviews. What is the reason?

enter image description here

2

There are 2 best solutions below

1
On

You should pass object of MainVC()

like below

let objOfMainVC = MainVC()
self.navigationController?.popToViewController(objOfMainVC, animated: false)

If you are using storyboard then

let storyBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let main = storyBoard.instantiateViewController(withIdentifier: "MainVC") as! MainVC // set withIdentifier to your identifier that was set in your storyboard.
self.navigationController?.pushViewController(main, animated: false)
1
On

You need the reference of MainVC. You can't just create a new instance of MainVC()

if let viewControllers = self.navigationController?.viewControllers {
    for vc in viewControllers {
        if let _ = vc as? MainVC {
            self.navigationController?.popToViewController(vc, animated: true)
            break
        }
    }
}

Or if your MainVC is root view controller of navigation controller.

self.navigationController?.popToRootViewController(animated: true)