newmaterialco/Modals

Programmatically dismiss modal from another view

tungxd96 opened this issue · 1 comments

Can we programmatically dismiss the modal from the modal content view (another view)? See the below example

I'm trying to dismiss the modal when clicking a button inside the ModalContentView by using a callback function to simply set the flag to false, but that doesn't work

MainView.swift

MainView()
        .modal(isPresented: $isModalVisible) {
            ModalContentView() {
                print("Dismiss")
                isModalVisible = false
            }
        }

Debug log is printed, flag is set, but nothing happens. When I changed to .toggle(), it only appended a new modal into a stack after 2 clicks which meant the false flag didn't close the modal.

Is there a way I can get around with this?

Hey, thanks for reaching out. The best way to programmatically dismiss the modal is by using ModalSystemDismissAction. Looks like we missed this in the docs 😅, will update it.

Here's how to use the dismissAction:

struct ModalContentView: View {
    @Environment(\.dismissModal) var dismissModal
    
    var body: some View {
        Button("Dismiss this modal!") {
            dismissModal()
        }
    }
}

Hope that helps!