SwiftUI Tap Gesture Start / End Actions

1.9k Views Asked by At

I try to add action when a tap gesture start and end but its not work !!! and bellow the example code.

@State private var opacity = 1.0

var body: some View {
Image(systemName: "plus.square.on.square")
            .opacity(opacity)
            .onTapGesture {
                opacity = 0.2
            }
            .gesture(
            TapGesture()
                .onEnded({ _ in
                    opacity = 1.0
                })
            )
}
1

There are 1 best solutions below

0
On

@TusharSharma is very close except for when using onLongPressGesture for detecting precisely the start and end of the gesture, only the onPressingChanged block matters.

This is a working example based on the code in question:

var body: some View {
  Image(systemName: "plus.square.on.square")
    .opacity(opacity)
    .onLongPressGesture(minimumDuration: .infinity) {
      // Do nothing as an action, only the state change matters.
    } onPressingChanged: { starting in
      withAnimation { opacity = starting ? 0.2 : 1.0 }
    }
}
@State 
private var opacity = 1.0

(The withAnimation part is optional, but I thought you'd want it for your example.)

minimumDuration: .infinity "holds" opacity on 0.2 for the entire duration of time while the user holds the press.