cesarcarlos
cesarcarlos

Reputation: 1431

Dismiss all modals in iOS with Swift 4

I am trying to achieve a navigation similar to the Netflix app for iOS. When you click on a movie, a modal window pops up with a close button. If within this movie I choose to see another movie then the second modal pops up and in addition to the close button, a back button appears. I can use the back button to dismiss one by one and the close button to return to the base screen.

I am able to dismiss a single view using

dismiss(animated: true, completion: nil)

but how can I return to the base screen closing all modals at once? Also, is modals the way to go? I chose this because I didn't want the navigation bar on top.

I'm working with Swift 4.2 in Xcode 10.

Upvotes: 6

Views: 4102

Answers (2)

Rukshan
Rukshan

Reputation: 8066

The way you are dismissing a ViewController is not the correct way. The presenting view controller is responsible for dismissing the view controller. Ideally you have to implement a protocol in your presenting ViewController and , dismiss your modal from your 'presenting' ViewController not 'presented' ViewController.

The reason why your way still works is, when a ViewController calls self.dimiss if there's nothing to dismiss UIKit will delegate it back to its parent. If you implement this correct way, once you dismiss , your presenting viewcontroller will dismiss , hence all the presented viewcontrollers will be dismissed instead of the last one.

From Apple Docs:

The presenting view controller is responsible for dismissing the view controller it presented. If you call this method on the presented view controller itself, UIKit asks the presenting view controller to handle the dismissal.

If you present several view controllers in succession, thus building a stack of presented view controllers, calling this method on a view controller lower in the stack dismisses its immediate child view controller and all view controllers above that child on the stack. When this happens, only the top-most view is dismissed in an animated fashion; any intermediate view controllers are simply removed from the stack. The top-most view is dismissed using its modal transition style, which may differ from the styles used by other view controllers lower in the stack.

If you want to retain a reference to the view controller's presented view controller, get the value in the presentedViewController property before calling this method.

The completion handler is called after the viewDidDisappear(_:) method is called on the presented view controller.

Upvotes: 6

yildirimatcioglu
yildirimatcioglu

Reputation: 311

try this

 self.navigationController?.viewControllers.removeAll(where: {$0.isModalInPopover})

Upvotes: 0

Related Questions