John Wu
John Wu

Reputation: 131

How to hide the modal by tapping the background in SwiftUI

After clicking a button, the modal shows or hides by changing the value of "show"

@State var show = false

but how can I hide the modal view by tapping the background when the modal shows just like the case of Instagram

enter image description here

I solve the problem by adding two onTapGesture, one on the modal view, the other on the VStack, if you have some better solution, please inform me, thanks.

VStack{
            Spacer()
            Reserve(selected: self.$seleted,show: self.$show)
                .offset(y:
                self.show ?
                    (UIApplication.shared.windows.last?.safeAreaInsets.bottom)!+15
                    : UIScreen.main.bounds.height
            )
                .onTapGesture {
                    print("xxx")
            }
        }
        .background(Color(UIColor.label.withAlphaComponent(self.show ? 0.2 : 0)))
        .onTapGesture {
                self.show = false
        }

Upvotes: 0

Views: 751

Answers (1)

Aye Chan
Aye Chan

Reputation: 1427

Here is my sample implementation. I hope it will help you.

struct ContentView: View {
    @State private  var show = false
    var body: some View {
        ZStack {
            Button(action: {
                self.show.toggle()
            }) {
                Text("Show sheet")
            }
            if show {
                CustomSheet(show: $show)
            }
        }
    }
}
struct CustomSheet: View {
    @Binding var show: Bool
    var body: some View {
        VStack {
            Spacer()
            Color.red.frame(height: 300)
        }.background(Color.gray.opacity(0.5).onTapGesture {
            self.show.toggle()
        })
    }
}

Upvotes: 1

Related Questions