SwiftUI: how to handle BOTH tap & long press of button?

Gerard picture Gerard · Oct 8, 2019 · Viewed 14.4k times · Source

I have a button in SwiftUI and I would like to be able to have a different action for "tap button" (normal click/tap) and "long press".

Is that possible in SwiftUI?

Here is the simple code for the button I have now (handles only the "normal" tap/touch case).

Button(action: {self.BLEinfo.startScan() }) {
                        Text("Scan")
                    } .disabled(self.BLEinfo.isScanning)

I already tried to add a "longPress gesture" but it still only "executes" the "normal/short" click. This was the code I tried:

Button(action: {self.BLEinfo.startScan() }) {
                        Text("Scan")
                            .fontWeight(.regular)
                            .font(.body)
                        .gesture(
                            LongPressGesture(minimumDuration: 2)
                                .onEnded { _ in
                                    print("Pressed!")
                            }
                        )
                    }

Thanks!

Gerard

Answer

norekhov picture norekhov · Oct 31, 2019

I tried many things but finally I did something like this:

    Button(action: {
    }) {
        VStack {
            Image(self.imageName)
                .resizable()
                .onTapGesture {
                    self.action(false)
                }
                .onLongPressGesture(minimumDuration: 0.1) {
                    self.action(true)
                }
        }
    }

It is still a button with effects but short and long press are different.