How do you detect a SwiftUI touchDown event with no movement or duration?

后端 未结 6 805
无人及你
无人及你 2020-12-19 02:21

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

6条回答
  •  独厮守ぢ
    2020-12-19 02:55

    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 setting isTapped to true. It will automatically be false 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 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.

提交回复
热议问题