我试图解散一个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从未被解散。有什么问题吗?


当前回答

试试这个:

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

其他回答

将你想要解散的视图嵌入到一个NavigationController中 添加一个BarButton与“完成”作为标识符 使用选定的Done按钮调用助理编辑器 为这个按钮创建一个IBAction 将这一行添加到括号中: 自我。disdisviewcontrolleranimated (true, completion: nil)

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

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

苹果文档:

呈现视图控制器负责解散它呈现的视图控制器

因此,仅仅从它自身调用dismiss方法是一个不好的做法。

如果你是模态呈现,你应该做的是:

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

作为参考,请注意您可能正在解散错误的视图控制器。例如,如果你有一个警告框或模式显示在另一个模式之上。(例如,您可以在当前模式警报的顶部显示Twitter帖子警报)。在这种情况下,您需要调用两次dismiss,或者使用一个unwind segue。

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

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

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

self.navigationController?.popViewController(animated: true)