SwiftUI: Dismiss all active sheet views

Viewed 938

How to dismiss all active sheets within an app? I have 2 app modes

switch appMode {
  case .locked:
    lockedView
  case .unlocked:
    contentView
}

When app mode change from one state to another and in current state there is some sheet view this sheet doesn't dissapear. Is there some SwiftUI solution?

2 Answers

You can use this line to dismissing all the presented sheets.

UIApplication.shared.windows.first?.rootViewController?.dismiss(animated: true, completion: nil)

iOS 15

'windows' was deprecated in iOS 15

let rootViewController = UIApplication.shared.connectedScenes
        .filter {$0.activationState == .foregroundActive }
        .map {$0 as? UIWindowScene }
        .compactMap { $0 }
        .first?.windows
        .filter({ $0.isKeyWindow }).first?.rootViewController
    
    rootViewController?.dismiss(animated: true) {
        // TODO: something
    }
Related