使用Swift编程以编程方式返回到上一个ViewController

261

当用户点击按钮时,我会将用户发送到一个页面。这个页面是一个UITableViewController

现在,如果用户点击单元格,我希望将其推回到上一个页面。

我考虑过像self.performSegue("back")....这样的方法,但这似乎是个坏主意。

正确的做法是什么?


15
self.navigationController?.popViewControllerAnimated(true)翻译:使用该代码可以让当前视图控制器返回上一个视图控制器。 - Kalpesh
16个回答

2

Swift 4.0 Xcode 10.0,最后一个视图控制器是TabViewController

如果您的最后一个视图控制器嵌入在TabViewController中,则以下代码将将您发送到根视图...

navigationController?.popToRootViewController(animated: true)
navigationController?.popViewController(animated: true)

但是如果您真的想返回到上一个视图(可能是Tab1、Tab2或Tab3视图..),您需要编写以下代码:

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

这对我很有用,我在我的TabView之后使用了一个视图 :)

2
我想建议另一种解决这个问题的方法。不要使用导航控制器来弹出视图控制器,而是使用取消连线。这种解决方案有一些非常重要的优点:
  1. 源视图控制器可以返回到任何其他目标视图控制器(不仅仅是上一个),而无需了解目标视图控制器的任何信息。
  2. 在故事板中定义推送和弹出连线,因此您的视图控制器中没有任何导航代码。
您可以在取消连线逐步指南中找到更多详细信息。前面的链接中更好地解释了如何操作,包括如何发送数据回来,但这里我将进行简要说明。

1)转到目标(而不是源)视图控制器并添加取消连线:

    @IBAction func unwindToContact(_ unwindSegue: UIStoryboardSegue) {
        //let sourceViewController = unwindSegue.source
        // Use data from the view controller which initiated the unwind segue
    }

2) 从视图控制器本身按住CTRL键并拖动到原始视图控制器中的退出图标:

Unwind from view controller

3) 选择刚才创建的取消操作函数:

Select unwind function

4) 选择取消线(segue),并给它一个名称:

Naming unwind segue

5)前往原视图控制器的任何位置,并调用取消返回操作的segue:

performSegue(withIdentifier: "unwindToContact", sender: self)

我发现当你的导航变得复杂时,采用这种方法会有很大收益。
希望这能帮助到某些人。

1

有关如何在Storyboard中将您的viewController嵌入到navigationController中的问题:

  1. 打开您的Storyboard,其中包含不同的viewController
  2. 点击您想要导航控制器从哪个视图控制器开始的视图控制器
  3. 在Xcode顶部,点击“编辑”
  4. -> 点击“嵌入”
  5. -> 点击“导航控制器”

0

我是这样做的

func showAlert() {
    let alert = UIAlertController(title: "Thanks!", message: "We'll get back to you as soon as posible.", preferredStyle: .alert)

    alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { action in
        self.dismissView()
    }))

    self.present(alert, animated: true)
}

func dismissView() {
    navigationController?.popViewController(animated: true)
    dismiss(animated: true, completion: nil)
}

0
如果您想关闭前两个视图控制器,只需调用popViewController两次,就像这样:
self.navigationController?.popViewController(animated: true)
self.navigationController?.popViewController(animated: true)

-4
我可以通过在导航控制器的 "viewDidDisappear" 中编写代码将页面重定向到根页面,
覆盖功能 func viewDidDisappear(_ animated: Bool) {        self.navigationController?.popToRootViewController(animated:true) }

这会使导航控制器回到根视图,即使你想在层次结构中向前移动。 - swiftyboi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接