How to know when SwiftUI presentation has finished?
Asked Answered
R

0

9

I want to know when my SwiftUI view has finished it's transition/animation in order to safely present additional views/modals.

Example:

I am in View A showing Sheet A. Within Sheet A I tap a button that dismisses Sheet A, transitions from View A to View B, and shows Sheet B on top of View B.

A naive implementation, e.g. initializing View B with a truthy binding/state to show Sheet B, will result in an error of the following form:

[Presentation] Attempt to present <_TtGC7SwiftUI29PresentationHostingControllerVS_7AnyView_: 0x107a03a00> on <_TtGC7SwiftUI19UIHostingControllerGVS_15ModifiedContentVS_7AnyViewVS_12RootModifier__: 0x107821800> (from <_TtGC7SwiftUI19UIHostingControllerVVS_19BridgedPresentation8RootView_: 0x107a1a200>) while a presentation is in progress.

This means we need to wait for View B to finish its transition before we can present Sheet B.

I am aware that I can...

  • ...add a NavigationStack/View to the .sheet() and just navigate from Sheet A to Sheet B. However, to provide the user with context, I want to have View B behind Sheet B.
  • ...wait some milliseconds before showing Sheet B, therefore likely ensuring that View B has finished the transition. E.g.
    DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
      // trigger sheet
    }
    

Waiting some seconds seems awefully non-deterministic to me, which is why I'm wondering whether there is a more elegant solution to this issue.

Regenaregency answered 23/2, 2023 at 12:13 Comment(1)
I also looking for a way to know when a view has finished it's presentation to start presenting another one. No luck, using the "deadline: .now() + 0.5" approach. But, please, anyone, give an answer please.Cosecant

© 2022 - 2024 — McMap. All rights reserved.