ios iOS如何以编程方式简单地返回到先前呈现/推送的视图控制器?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38741556/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
iOS how to simple return back to previous presented/pushed view controller programmatically?
提问by Matrosov Alexander
How to return back to previous view controller programmatically? I found this answer, but there is an example that demonstrate how to go back if we have navigation stack:
如何以编程方式返回上一个视图控制器?我找到了这个答案,但有一个例子演示了如果我们有导航堆栈,如何返回:
navigationController?.popViewControllerAnimated(true)
It's ok in case my queue of controllers based on navigation controller. But usually we use storyboard where we specify segue that marked with keyword Showthat means we don't care about navigation push or present new view controllers. So in this case I presume there is only option with unwind view controller via segue, but maybe there is some simple call that I can do programmatically to go back to my previous view controller without checking if my stack of view controllers contain UINavigationController
or not.
如果我的控制器队列基于导航控制器,那没关系。但通常我们使用故事板,在其中指定带有关键字Show标记的 segue,这意味着我们不关心导航推送或呈现新的视图控制器。所以在这种情况下,我认为只有通过 segue 展开视图控制器的选项,但也许有一些简单的调用,我可以通过编程方式返回到我以前的视图控制器,而无需检查我的视图控制器堆栈是否包含UINavigationController
。
I am looking for something simple like self.performSegueToReturnBack
.
我正在寻找像self.performSegueToReturnBack
.
回答by Prajeet Shrestha
You can easily extend functionality of any inbuilt classes or any other classes through extensions. This is the perfect use cases of extensions in swift.
您可以通过扩展轻松扩展任何内置类或任何其他类的功能。这是 swift 中扩展的完美用例。
You can make extension of UIViewController like this and use the performSegueToReturnBackfunction in any UIViewController
您可以像这样扩展 UIViewController 并在任何 UIViewController 中使用performSegueToReturnBack函数
Swift 2.0
斯威夫特 2.0
extension UIViewController {
func performSegueToReturnBack() {
if let nav = self.navigationController {
nav.popViewControllerAnimated(true)
} else {
self.dismissViewControllerAnimated(true, completion: nil)
}
}
}
Swift 3.0
斯威夫特 3.0
extension UIViewController {
func performSegueToReturnBack() {
if let nav = self.navigationController {
nav.popViewController(animated: true)
} else {
self.dismiss(animated: true, completion: nil)
}
}
}
Note:
笔记:
Someone suggested that we should assign _ = nav.popViewControllerAnimated(true)
to an unnamed variable as compiler complains if we use it without assigning to anything. But I didn't find it so.
有人建议我们应该分配_ = nav.popViewControllerAnimated(true)
给一个未命名的变量,因为编译器会抱怨如果我们在没有分配任何东西的情况下使用它。但我没有发现。
回答by Giggs
Best answer is this: _ = navigationController?.popViewController(animated: true)
最佳答案是:_ = navigationController?.popViewController(animated: true)
Taken from here: https://stackoverflow.com/a/28761084/2173368