Search code examples
iosswiftuiviewcontrolleruinavigationcontroller

Swift - Dismiss two controllers wrong order


I have something like this in my Storyboard: NavigationController -> A -> B -> C where A, B and C are ViewControllers. I am staying in C where I have variable representing B controller and doing something like this:

    controllerB?.navigationController?.popViewController(animated: true)
    self.navigationController?.popViewController(animated: true)

Which should dismiss B controller and then C. But when I do this in simulator, I see C controller beeing dismissed first and after it I see B controller for a while before it is dismissed too. I tried delay like this:

DispatchQueue.main.asyncAfter(deadline: .now() + 5.0)

But it is not working either Can you help me? And is it even possible to dissmiss B before C?


Solution

  • You can't call pop twice in a row like you're trying to do, and using timers is fragile and not recommended. (It's a shame the pop methods don't take a completion handler like the modal dismiss methods do.)

    Just use popToViewController(_:animated:). Send the message to self.navigationController, and send A as the view controller to pop to.

    If A is the root, just use self.navigationController.popToRootViewController(animated:true)