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


当前回答

苹果文档:

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

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

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

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

其他回答

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

斯威夫特3:

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

OR

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

self.navigationController?.popViewController(animated: true)

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

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

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

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

斯威夫特2

navigationController.popViewControllerAnimated(true)

斯威夫特4

navigationController?.popViewController(animated: true)

dismiss(animated: true, completion: nil)
@IBAction func back(_ sender: Any) {
        self.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)
   }
   ...
}