我试图解散一个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)
}

其他回答

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

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

根据我的经验,我添加了一个方法来解散我作为UIViewController的扩展:

extension UIViewController {
    func dismissMe(animated: Bool, completion: (()->())?) {
        var count = 0
        if let c = self.navigationController?.viewControllers.count {
            count = c
        }
        if count > 1 {
            self.navigationController?.popViewController(animated: animated)
            if let handler = completion {
                handler()
            }
        } else {
            dismiss(animated: animated, completion: completion)
        }
    }
}

然后我调用这个方法来解散任何UIViewController子类中的视图控制器。例如,在取消动作中:

class MyViewController: UIViewController {
   ...
   @IBAction func cancel(sender: AnyObject) {
     dismissMe(animated: 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")
  }    
}

如果你在父VC中使用当前方法,那么你应该调用这个函数,来解散子VC

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

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

self.navigationController?.popViewController(animated: true)

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

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