问题
I am presenting a modalviewcontroller from another modalviewcontroller. When I dismiss the second modalviewcontroller both the first and second modalviewcontroller should get dismissed. I tried to access the first modalview like
[self.view.superview dismissmodalviewcontroller];
but it is showing error. What is the right way to get a ref to the first modalViewController from the second one and invoke the dismiss method from it?
回答1:
Its like this.
A presents B. Here, A is parent of B (Here, A.modalViewController will be B and B.parentViewController will be A)
And B presents C. Here, B is parent of C (Here, B.modalViewController will be C and C.parentViewController will be B)
According to apple guidelines, its responsibility of parent controller to dismiss its child controller.
So if you want to dismiss controller C, you call dismissModalViewController at C.parentViewController. As C's parent is B, thus B is dismissing its modal (child) controller that it presented.
But you want to even dismiss B. Its responsibility of B's parent to dismiss B. So you need to say [B.parentViewController dismissModalViewControllerAnimated: YES];
Thus, you need to get B from C as C.parentViewController (Don't forget to typecast here). Then you say that [B.parentViewController dismissModalViewControllerAnimated: YES];
回答2:
Try [self.parentViewController dismissModalViewControllerAnimated:YES];
This will dismiss both modal view controllers
回答3:
The dismissModalViewControllerAnimated: method is part of the UIViewController class, not the of UIView. So you need to do
[self.parentViewController dismissModalViewControllerAnimated:YES];
instead of calling it on self.view.superview.
回答4:
To clarify even further, what you will probably need is something like this:
[self.parentViewController.parentViewController dismissModalViewControllerAnimated:YES];
回答5:
i just found it's answer, may be it will help somebody we need just one line of code
[self.presentingViewController.presentingViewController dismissModalViewControllerAnimated:YES];
回答6:
Sadly it the view always flick to the first modal in the stack then perform the animation.
I fixed it with a custom animation:
let transition: CATransition = CATransition()
transition.duration = 0.5
transition.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
transition.type = kCATransitionReveal
transition.subtype = kCATransitionFromBottom
self.view.window!.layer.add(transition, forKey: nil)
self.presentingViewController?.presentingViewController?.dismiss(animated: false, completion: nil)
来源:https://stackoverflow.com/questions/5935462/dismiss-modalviewcontroller-from-another-modalviewcontroller