Beware the cancelled interactive dismiss of SwiftUI popovers

Development / iOS / Making of Captionista

Another in the long serious of little niggles with SwiftUI popovers on iPad. This time, it’s more serious but there is a workaround.

If you show a sheet the user can interactively dismiss these on iOS, but they can also cancel the dismissal by bringing the sheet back up near to its “shown” position.

If they do this and you reference SwiftUI environment objects in the views within the sheet, you will likely get a crash as your View attempts to re-render but the environment is no longer valid. It seems when the dismiss starts the environment of the View is invalidated, rather than when the dismiss ends.

Workaround: Don’t use the environment for sheets. Pass in all required values to the initialiser of the View you are presenting, usually by having an ancestor that is presenting sheet read the values from the environment.

The Author

Marc Palmer (Twitter, Mastodon) is a consultant and software engineer specialising in Apple platforms. He currently works on the iOS team of Concepts sketching app, as well as his own apps like video subtitle app Captionista. He created the Flint open source framework. He can also do a pretty good job of designing app products. Don't ask him to draw anything, because that's really embarrassing. You can find out more here.