
Managing the presentation and dismissal of views in SwiftUI is a fundamental task, but relying solely on the environment’s .dismiss
action can lead to architectural challenges as your application grows. While convenient for simple cases, scattering dismissal logic directly within views makes the app’s flow harder to track and maintain.
A more robust and maintainable approach centers around state-driven development. Instead of commanding a view to dismiss itself, you control its presentation status using a state variable. SwiftUI’s declarative nature means that when this state changes, the UI automatically updates, including presenting or dismissing views attached to that state.
For instance, presenting a modal sheet or full-screen cover is commonly done using modifiers like .sheet(isPresented: ...)
or .fullScreenCover(isPresented: ...)
that take a Binding<Bool>
. By controlling the underlying @State
boolean value, you determine if the view is shown or hidden. Setting the boolean to true
presents the view; setting it back to false
dismisses it.
This pattern extends to presenting views based on selected data, using an optional @State
variable (e.g., @State var selectedItem: Item?
). Attaching a sheet with .sheet(item: $selectedItem)
means the sheet is presented when selectedItem
becomes non-nil
and dismissed when it becomes nil
. The state variable holds the data the presented view needs.
The key benefit of this state-driven approach is centralization. The logic for why a view is presented or dismissed resides with the state that controls it, often managed in a parent view or a dedicated View Model (using @StateObject
or @ObservedObject
). This makes the codebase easier to understand, debug, and refactor. You can see the entire presentation flow by looking at how the state variable is managed, rather than searching for .dismiss
calls scattered across different views.
Embracing state-driven presentation significantly improves your SwiftUI application’s architecture and testability, leading to more predictable behavior and reducing complexity in the long run. It aligns perfectly with SwiftUI’s core principles, making your codebase more resilient and easier to evolve.
Source: https://itnext.io/say-goodbye-to-dismiss-a-state-driven-path-to-more-maintainable-swiftui-b42c487a6b2b?source=rss—-5b301f10ddcd—4