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


当前回答

如果你这样做,我猜你可能不会在控制台得到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")
  }    
}

其他回答

如果你想解散你的视图控制器使用这个。这段代码是用按钮动作来编写的,以消除VC

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

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

斯威夫特3:

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

OR

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

self.navigationController?.popViewController(animated: true)

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

如果你这样做,我猜你可能不会在控制台得到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")
  }    
}

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

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

斯威夫特2

navigationController.popViewControllerAnimated(true)

斯威夫特4

navigationController?.popViewController(animated: true)

dismiss(animated: true, completion: nil)