简体   繁体   English

ios swift - 解除导航控制器的根视图控制器

[英]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. 并在两者上获得NSException。

Please advise. 请指教。

Swift 3: 斯威夫特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 . 如果你正在推动你的ViewController ,你应该使用popNavigation堆栈中删除该ViewController并登陆前一个ViewController Try this ... 试试这个 ......

self.navigationController?.popViewControllerAnimated(true);

SWIFT 3 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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