I wanted to add a dismiss
button to a sheet on SwiftUI.
Since I also want to control the presentation from code, I put the presented state in a view model. Here is a simplified version of the code:
final class ViewController: ObservableObject {
@Published var showSheet: Bool = false
}
struct ContentView: View {
@StateObject private var viewController = ViewController()
var body: some View {
Button("Show sheet") {
viewController.showSheet = true
}
.padding()
.sheet(isPresented: $viewController.showSheet, content: {
MySheetView()
})
}
}
struct MySheetView: View {
@Environment(\.dismiss) private var dismiss
var body: some View {
NavigationView {
Text("Hello from the sheet")
.toolbar {
ToolbarItem(placement: .navigationBarTrailing, content: {
Button("Dismiss") {
dismiss()
}
})
}
}
}
}
If I use the dismiss
button, I get the warning:
Publishing changes from within view updates is not allowed, this will cause undefined behavior.
just swiping down the sheet works fine.
Am I using something wrong here?
Xcode Version 14.0 (14A309)