简体   繁体   中英

ios swift - dismiss root view controller of navigation controller

I'm opening a navigation controller from a button click of my main view controller.

I programatically created a left bar button item on the navigation controller which I want to dismiss the nav controller and go back to my main controller.

I'm essentially going back on the root view controller of the navigation controller.

I've tried

navigationController?.dismissViewControllerAnimated(true, completion: nil)

and

self.dismissViewControllerAnimated(true, completion: nil)

and get an NSException on both.

Please advise.

Swift 3:

self.view.window!.rootViewController?.dismiss(animated: false, completion: nil)

It will dismiss all the presented view controllers and remain root view controller.

If you are pushing your ViewController , you should use pop to remove that ViewController from Navigation Stack and land on the previous ViewController . Try this ...

self.navigationController?.popViewControllerAnimated(true);

SWIFT 3

_ = navigationController?.popViewController(animated: true);

当您使用presentViewController(可能是导航堆栈的根视图控制器或独立视图控制器)显示viewController时,dismissViewController工作。

self.presentingViewController?.presentingViewController?.dismissViewControllerAnimated(true, completion: nil)

尝试这个 :)

A year later.. The exception indicates that there is something wrong with the selector that you provide to the action param, when adding the left bar button.

Something like this should work:

creating bar button item:

let backBarButton = UIBarButtonItem.init(barButtonSystemItem: UIBarButtonSystemItem.stop, target: self, action: #selector(dismissView))

dismiss root view controller:

func dismissView() {
    self.dismiss(animated: true, completion: nil)
}

Apple Dev已经提供了非常简单的代码

self.navigationController?.popToRootViewController(animated: false)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM