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


当前回答

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

斯威夫特3:

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

OR

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

self.navigationController?.popViewController(animated: true)

其他回答

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

这是一种方法来解散当前的视图控制器并移回之前的视图控制器。您只能通过故事板来实现这一点。

开放的故事板 右键单击取消按钮并将其拖到前一个视图控制器,在那里您想移动回前一个控制器 现在释放右键点击,你可以看到一些行动执行取消按钮 现在从列表中选择“弹出窗口呈现”选项 现在你可以通过点击取消按钮来取消当前视图

请试试这个,它对我很有效。

第二种方法-使用- navigationController.popViewControllerAnimated(true)

最好的运气. .

如果你这样做,我猜你可能不会在控制台得到println消息,

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

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

苹果文档:

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

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

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

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

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

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

斯威夫特2

navigationController.popViewControllerAnimated(true)

斯威夫特4

navigationController?.popViewController(animated: true)

dismiss(animated: true, completion: nil)