Is it possible to make a modal non-dismissible in

2020-02-12 09:56发布

问题:

I am creating an App where the login / register part is inside a modal, which is shown if the user is not logged in.

The problem is, that the user can dismiss the modal by swiping it down...

Is it possible to prevent this?

var body: some View {
    TabView(selection: $selection) {
        App()
    }.sheet(isPresented: self.$showSheet) { // This needs to be non-dismissible
        LoginRegister()
    }
}

Second example:

I am using a modal to ask for information. The user should not be able to quit this process except by dismissing the modal with save button. The user has to input information before the button works. Unfortunately the modal can be dismissed by swiping it down.

Is it possible to prevent this?

回答1:

You can try to do this by using a highPriorityGesture. Of course the blue Rectangle is only for demonstration but you would have to use a view which is covering the whole screen.

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

    let gesture = DragGesture()

    var body: some View {

        Rectangle()
            .fill(Color.blue)
            .frame(width: 300, height: 600)
            .highPriorityGesture(gesture)

            .overlay(
                VStack{
                    Button("Close") {
                        self.presentationMode.value.dismiss()
                    }.accentColor(.white)
                    Text("Modal")
                        .highPriorityGesture(gesture)
                    TextField("as", text: .constant("sdf"))
                        .highPriorityGesture(gesture)
                } .highPriorityGesture(gesture)
        )
            .border(Color.green)
    }
}


回答2:

This is a common problem and a "code smell"... well not really code but a "design pattern smell" anyway.

The problem is that you are making your login process part of the rest of the app.

Instead of presenting the LoginRegister over the App you should really be showing either App or LoginRegister.

i.e. you should have some state object like userLoggedIn: Bool or something and depending on that value you should show either App or LoginRegister.

Just don't have both in the view hierarchy at the same time. That way your user won't be able to dismiss the view.



标签: swiftui