Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect touch outside Button in SwiftUI

Tags:

swiftui

I have a reset button that asks for confirmation first. I would like to set isSure to false is the user touches outside the component.

Can I do this from the Button component?

Here is my button:

struct ResetButton: View {
    var onConfirmPress: () -> Void;
    @State private var isSure: Bool = false;

    var body: some View {
        Button(action: {
            if (self.isSure) {
                self.onConfirmPress();
                self.isSure.toggle();
            } else {
                self.isSure.toggle();
            }
        }) {
            Text(self.isSure ? "Are you sure?" : "Reset")
        }
    }
}
like image 890
Kevin Amiranoff Avatar asked Nov 08 '25 16:11

Kevin Amiranoff


1 Answers

here is one way to do it:

struct ContentView: View {

var onConfirmPress: () -> Void

@State private var isSure: Bool = false

var body: some View {
    GeometryReader { geometry in
        ZStack {
            // a transparent rectangle under everything
            Rectangle()
                .frame(width: geometry.size.width, height: geometry.size.height)
                .opacity(0.001)   // <--- important
                .layoutPriority(-1)
                .onTapGesture {
                    self.isSure = false
                    print("---> onTapGesture self.isSure : \(self.isSure)")
            }
            Button(action: {
                if (self.isSure) {
                    self.onConfirmPress()
                }
                self.isSure.toggle()
            }) {
                Text(self.isSure ? "Are you sure?" : "Reset").padding(10).border(Color.black)
            }
        }
    }
}
}
like image 100
workingdog support Ukraine Avatar answered Nov 11 '25 02:11

workingdog support Ukraine



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!