How to Implement Dismiss Callback for Sheet in iOS SwiftUI
In SwiftUI, sheets are a convenient way to present secondary views or modals. While it’s easy to show and dismiss sheets, you might want to execute some code when a sheet is dismissed.
This is where the onDismiss parameter comes in handy. In this blog post, we’ll explore how to implement a dismiss callback for sheets in SwiftUI using the onDismiss parameter.
Default Sheet Behavior
By default, SwiftUI provides a simple way to present sheets using the .sheet
modifier. However, it doesn’t automatically notify you when the sheet is dismissed.
Add Dismiss Callback
Example Code
import SwiftUI
struct ContentView: View {
@State private var showModal = false
var body: some View {
Button("Show Modal") {
showModal.toggle()
}
.sheet(isPresented: $showModal, onDismiss: {
print("Modal Closed!")
}) {
VStack{
Text("Hello, I'm a modal!")
Button("Dismiss") {
showModal = false
}
}
}
}
}
Code Explanation
onDismiss: { print("Modal Closed!") }
: TheonDismiss
parameter allows you to specify a closure that will be executed when the sheet is dismissed. In this example, it prints “Modal Closed!” to the console.Button("Dismiss") { showModal = false }
: Inside the sheet, we have a button that sets theshowModal
state variable tofalse
, effectively dismissing the sheet and triggering theonDismiss
closure.
Why Use a Dismiss Callback?
Here are some reasons why you might want to use a dismiss callback:
- Data Refresh: You might need to refresh data or update the UI when a sheet is dismissed.
- Analytics: Tracking when a sheet is dismissed can provide valuable analytics data.
- User Experience: You might want to show a confirmation message or perform some other action when a sheet is dismissed to enhance the user experience.
The onDismiss
parameter in SwiftUI provides a simple and effective way to execute code when a sheet is dismissed. Whether you need to refresh data, track analytics, or enhance the user experience, this parameter offers a straightforward solution.