Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 612
Gerard Avatar asked Oct 08 '19 10:10

Gerard


2 Answers

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.

like image 117
norekhov Avatar answered Sep 23 '22 05:09

norekhov


Combining a high priority gesture and a simultaneous gesture should do the trick.

Button(action: {}) {     Text("A Button") } .simultaneousGesture(     LongPressGesture()         .onEnded { _ in             print("Loooong")         } ) .highPriorityGesture(TapGesture()                         .onEnded { _ in                             print("Tap")                         }) 

Found this a handy pattern when interacting with other views as well.

like image 22
Jensie Avatar answered Sep 24 '22 05:09

Jensie