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)
Same. I encountered the same problem. Swiping down on sheets work fine, click on a button give purple warning.
Forgot to add this.... I ran the exact same code on macOS and no warning at all. On Mac there is no swipe down. So the only option is clicking dismiss button on a sheet. And after clicking the dismiss, no warning. Seems to be there is a bug in iOS.