我试图解散一个ViewController在一个IBAction调用遣散ViewController

  @IBAction func cancel(sender: AnyObject) {
    self.dismissViewControllerAnimated(false, completion: nil)
    println("cancel")
}

@IBAction func done(sender: AnyObject) {
    self.dismissViewControllerAnimated(false, completion: nil)
    println("done")
}

我可以在控制台输出中看到println消息,但ViewController从未被解散。有什么问题吗?


当前回答

不要创建任何从取消或完成到其他VC的segue,只把这段代码写在你的按钮@IBAction上

@IBAction func cancel(sender: AnyObject) {
    dismiss(animated: false, completion: nil)
}

其他回答

在Swift 4.1和Xcode 9.4.1中

如果你使用pushViewController来呈现新的视图控制器,使用这个

self.navigationController?.popViewController(animated: false)

在Swift 3.0到4.0中,只需在函数中输入以下内容即可:

self.dismiss(animated: true, completion: nil)

或者如果你在导航控制器中,你可以“弹出”它:

self.navigationController?.popViewController(animated: true)

因为你使用了push presenting viewController,因此,你可以使用

self.dismiss(animated: false, completion: nil)

我有办法解决你的问题。如果你使用模态显示视图,请尝试下面的代码来解除视图控制器:

斯威夫特3:

self.dismiss(animated: true, completion: nil)

OR

如果你使用push segue来呈现视图

self.navigationController?.popViewController(animated: true)

从你的图片来看,你似乎是用push来呈现ViewController的

disdisviewcontrolleranimated用于关闭使用modal呈现的viewcontroller

斯威夫特2

navigationController.popViewControllerAnimated(true)

斯威夫特4

navigationController?.popViewController(animated: true)

dismiss(animated: true, completion: nil)