iOS如何简单地以编程方式返回到先前呈现/推送的视图控制器? [英] iOS how to simple return back to previous presented/pushed view controller programmatically?

查看:98
本文介绍了iOS如何简单地以编程方式返回到先前呈现/推送的视图控制器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何以编程方式返回上一个视图控制器?我找到了这个回答,但有一个例子可以证明如果我们有导航堆栈怎么回去:

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)

如果我的控制器队列基于导航控制器,那就没关系。但是通常我们使用故事板,我们指定用关键字显示标记的segue,这意味着我们不关心导航推送或呈现新的视图控制器。所以在这种情况下我假设只有通过segue的unwind视图控制器的选项,但也许有一些简单的调用,我可以编程方式返回到我以前的视图控制器,而不检查我的视图控制器堆栈是否包含 UINavigationController 与否。

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 Show that 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.

我正在寻找像 self.performSegueToReturnBack 。

推荐答案

您可以通过扩展轻松扩展任何内置类或任何其他类的功能。这是swift中扩展的完美用例。

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.

你可以像这样扩展UIViewController并在任何UIViewController中使用 performSegueToReturnBack 函数

You can make extension of UIViewController like this and use the performSegueToReturnBack function in any UIViewController

Swift 2.0

extension UIViewController {
    func performSegueToReturnBack()  {
        if let nav = self.navigationController {
            nav.popViewControllerAnimated(true)
        } else {
            self.dismissViewControllerAnimated(true, completion: nil)
        }
    }
}

Swift 3.0

extension UIViewController {
    func performSegueToReturnBack()  {
        if let nav = self.navigationController {
            nav.popViewController(animated: true)
        } else {
            self.dismiss(animated: true, completion: nil)
        }
    }
}

注意:

有人建议我们应该将 _ = nav.popViewControllerAnimated(true)分配给一个未命名的变量,因为如果我们使用它而不分配任何内容,编译器会抱怨。但我没有发现它。

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.

这篇关于iOS如何简单地以编程方式返回到先前呈现/推送的视图控制器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆