Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dismiss sheet SwiftUI

Tags:

swiftui

I'm trying to implement a dismiss button for my modal sheet as follows:

struct TestView: View {
    @Environment(\.isPresented) var present
    var body: some View {
        Button("return") {
            self.present?.value = false
        }
    }
}

struct DataTest : View {
    @State var showModal: Bool = false

    var modal: some View {
        TestView()
    }
    var body: some View {
        Button("Present") {
            self.showModal = true
        }.sheet(isPresented: $showModal) {
            self.modal
        }
    }
}

But the return button when tapped does nothing. When the modal is displayed the following appears in the console:

[WindowServer] display_timer_callback: unexpected state (now:5fbd2efe5da4 < expected:5fbd2ff58e89)

If you force unwrap present you find that it is nil

How can I dismiss .sheet programmatically?

like image 755
Brandon Bradley Avatar asked Jul 27 '19 14:07

Brandon Bradley


People also ask

How do I dismiss a sheet in SwiftUI?

The first option is to tell the view to dismiss itself using its presentation mode environment key. Any view can read its presentation mode using @Environment(\. presentationMode) , and calling wrappedValue. dismiss() on that will cause the view to be dismissed.

How do I delete a view in SwiftUI?

By default, SwiftUI uses a fade animation to insert or remove views, but you can change that if you want by attaching a transition() modifier to a view.

How do I create a bottom sheet in SwiftUI?

Starting from iOS 16, the SwiftUI framework comes with a new modifier called presentationDetents for presenting a resizable bottom sheet. Text("This is the expandable bottom sheet." You specify a set of detents in the presentationDetents modifier. As shown above, the bottom sheet supports both medium and large size.


1 Answers

Use presentationMode from the @Environment.

Beta 6

struct SomeView: View {
    @Environment(\.presentationMode) var presentationMode

    var body: some View {
        VStack {
            Text("Ohay!")
            Button("Close") {
                self.presentationMode.wrappedValue.dismiss()
            }
        }
    }
}
like image 158
backslash-f Avatar answered Oct 11 '22 03:10

backslash-f