我试图解散一个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中使用当前方法,那么你应该调用这个函数,来解散子VC

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

如果你用push方法调用子VC,用这个方法来解散子VC

self.navigationController?.popViewController(animated: true)

其他回答

在Swift 3.0中

如果你想解散一个呈现的视图控制器

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

如果你呈现一个没有导航控制器的控制器,你可以从呈现控制器的一个方法调用下面的代码。

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

如果你的ViewController是模态呈现的,可选的presentingViewController将不是nil,代码将被执行。

试试这个:

@IBAction func close() {
  dismiss(animated: true, completion: nil)
}

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

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

斯威夫特2

navigationController.popViewControllerAnimated(true)

斯威夫特4

navigationController?.popViewController(animated: true)

dismiss(animated: true, completion: nil)

如果你正在以模态方式呈现一个ViewController,并且想要回到根ViewController,在你回到根ViewController之前,注意解散这个模态呈现的ViewController,否则这个ViewController将不会从内存中移除,并导致内存泄漏。