-->

self.dismiss does nothing on 3rd level segue

2019-05-24 11:50发布

问题:

I have a view controller embedded in a navigation controller. I segue to a view controller via a "show" segue. From there I navigate to a tableviewcontroller via a "show" segue. The navigation bar shows up with the back button but upon didclickrow self.dismiss does nothing. The completion block never executes. I'm baffled. There has to be some rule I don't understand about view controllers.

self.dismiss(animated: true, completion: {
    print( "THIS NEVER EXECUTES AND NOTHING HAPPENS" )
})    

回答1:

The "show segue" is used to push a view controller. So your code will not work as you are trying to dismiss the view controller that was not presented.

You should dismiss only when a view controller is presented or you have used a "Present Modally Segue" type.

You should use popViewController when you have used "Push Segue" type or have pushed a view controller.

self.navigationController?.popViewController(animated: true)


回答2:

While in a UINavigationController, You should use the function

_ = navigationController?.popViewController(animated: true)

Or if you want to go back to the very top level view, use:

_ = navigationController?.popToRootViewController(animated: true)

The Apple Documentation for this function explains:

This method removes the top view controller from the stack and makes the new top of the stack the active view controller. If the view controller at the top of the stack is the root view controller, this method does nothing.