Search code examples
swiftswiftuigesture

Can't apply ".onChanged" method for TapGesture in SwiftUI


I'm getting the following error if trying to run the code below:

// Type 'TapGesture.Value' (aka '()') cannot conform to 'Equatable'

Here's a code:

struct PressButton: View {
    
    @Binding var pressed: Bool
                
    var body: some View {

        ZStack {            
            Circle()
                .gesture(
                    TapGesture()
                        .onChanged { _ in pressed = true }    // ERROR
                        .onEnded { _ in pressed = false }
                )
        }
    }
}

However, .onEnded { _ in } method is working fine.


Solution

  • As the documentation of onChanged states, the method is only available on Gesture when Gesture.Value is Equatable. However, TapGesture.Value is Void, which is not Equatable, hence TapGesture doesn't have the onChanged method.

    However, onEnded is available on all Gesture conformant types.

    A TapGesture holds no state, it is only called after the tap has happened.

    What you are looking for is LongPressGesture, which does expose state as a Bool.