以编程方式返回到Swift中的前一个ViewController

Chr*_*ian 192 ios segue swift

我通过点击按钮将用户发送到页面.这个页面是一个UITableViewController.

现在,如果用户点击一个单元格,我想将他推回到上一页.

我想过类似的东西,self.performSegue("back")....但这似乎是一个坏主意.

这样做的正确方法是什么?

Pra*_*I V 485

斯威夫特3:

如果要返回上一个视图控制器

_ = navigationController?.popViewController(animated: true)
Run Code Online (Sandbox Code Playgroud)

如果要返回根视图控制器

_ = navigationController?.popToRootViewController(animated: true)
Run Code Online (Sandbox Code Playgroud)

  • 对于Swift 3,它是`.popViewController(animated:true)` (34认同)
  • 嘘任何警告:`_ = self.navigationController?.popToRootViewController(animated:true)` (7认同)
  • @JDDelgado这是您向用户发送数据的方式,http://stackoverflow.com/questions/12561735/what-are-unwind-segues-for-and-how-do-you-use-them (4认同)

Vya*_*lav 47

Swift 3,Swift 4

if movetoroot { 
    navigationController?.popToRootViewController(animated: true)
} else {
    navigationController?.popViewController(animated: true)
}
Run Code Online (Sandbox Code Playgroud)

navigationController是可选的,因为可能没有.


小智 33

斯威夫特3

我可能会在答案中迟到,但对于快速3,你可以这样做:

override func viewDidLoad() {
    super.viewDidLoad()

    navigationItem.leftBarButtonItem = UIBarButtonItem(title: "< Back", style: .plain, target: self, action: #selector(backAction))

    // Do any additional setup if required.
}

func backAction(){
    //print("Back Button Clicked")
    dismiss(animated: true, completion: nil)
}
Run Code Online (Sandbox Code Playgroud)

  • 那不是'完全'正确的.如果你提出一个包含自己导航的视图控制器,并且在推动视图控制器后使用该方法`dismiss:`它不仅会关闭当前视图控制器,还会关闭根视图控制器,这不是这里要求的. (2认同)
  • 问题没有询问用户是否有导航控制器.对于没有导航控制器,这是最简单和最好的答案.这应该是公认的答案. (2认同)

小智 28

斯威夫特4

有两种方法可以返回/返回上一个ViewController:

  1. 第一种情况:如果您使用过:self.navigationController?.pushViewController(yourViewController, animated: true) 在这种情况下您需要使用self.navigationController?.popViewController(animated: true)
  2. 第二种情况:如果您使用过:self.present(yourViewController, animated: true, completion: nil) 在这种情况下您需要使用self.dismiss(animated: true, completion: nil)

在第一种情况下,请确保将ViewController嵌入到故事板中的navigationController


spe*_*.sm 18

如果你UIViewController在一个UIViewControllerie ...中提出了一个

// Main View Controller
self.present(otherViewController, animated: true)
Run Code Online (Sandbox Code Playgroud)

只需调用该dismiss功能:

// Other View Controller
self.dismiss(animated: true)
Run Code Online (Sandbox Code Playgroud)


mid*_*n p 13

迅速5以上

情况1:与导航控制器一起使用

self.navigationController?.popViewController(animated: true)
Run Code Online (Sandbox Code Playgroud)

情况2:与当前视图控制器一起使用

self.dismiss(animated: true, completion: nil)
Run Code Online (Sandbox Code Playgroud)


小智 11

如果Segue是'Show'或'Push',那么你可以在UINavigationController的实例上调用"popViewController(animated:Bool)".或者,如果segue有点"存在",那么调用"dismiss(动画:Bool,完成:(() - > Void)?)"与UIViewController的实例


Amr*_*gry 7

对于swift 3,您只需要编写以下代码行

_ = navigationController?.popViewController(animated: true)
Run Code Online (Sandbox Code Playgroud)