I\'m trying to detect when a finger first makes contact with a view in SwiftUI. I could do this very easily with UIKit Events but can\'t figure this out in SwiftUI.
I
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:
@GestureState
property wrapper automatically resets its value to the original value when the gesture ends. This way you only have to worry about setting isTapped
to true
. It will automatically be false
again when the interaction ends.updating
modifier has this weird closure with three parameters. In this case we are only interested in the middle one. It's an inout
parameter to the wrapped value of the GestureState
, so we can set it here. The first parameter has the current value of the gesture; the third one is a Transaction
containing some animation context.