You can use the .updating
modifier like this:
struct TapTestView: View {
@GestureState private var isTapped = false
var body: some View {
let tap = DragGesture(minimumDistance: 0)
.updating($isTapped) { (_, isTapped, _) in
isTapped = true
}
return Text("Tap me!")
.foregroundColor(isTapped ? .red: .black)
.gesture(tap)
}
}
Some notes:
- The zero minimum distance makes sure the gesture is immediately recognised
- The
@GestureState
property wrapper automatically resets its value to the original value when the gesture ends. This way you only have to worry about settingisTapped
totrue
. It will automatically befalse
again when the interaction ends. - The
updating
modifier has this weird closure with three parameters. In this case we are only interested in the middle one. It’s aninout
parameter to the wrapped value of theGestureState
, so we can set it here. The first parameter has the current value of the gesture; the third one is aTransaction
containing some animation context.