Call the onTapGesture method on a View that has child views that have onTapGestures without overriding

Viewed 65

I want to be able to add a onTapGesture{} to a View without overriding the onTapGesture{}s that may be part of the that view already.

Example:

struct NotAPieceOfLettuce: View {
    var body: some View{
      Text("what am I?").onTapGesture{print("I am not a piece of lettuce")}
     }
}

struct Banana: View {
    var body: some View{
       NotAPieceOfLettuce().onTapGesture{print("just a banana, not lettuce")}
    }
}

The code above will actually print just a banana, not lettuce on tap, although I want it to print I am not a piece of lettuce and also just a banana, not lettuce...

I have tried .simultaneousGesture() but the program output is no different than what it is with the example code above.

Thank you for reading, WiseEye YT.

2 Answers

Simultaneous gesture should be specified at both sides, like

struct NotAPieceOfLettuce: View {
    var body: some View{
      Text("what am I?")
        .simultaneousGesture(TapGesture().onEnded{print("I am not a piece of lettuce")})
     }
}

struct Banana: View {
    var body: some View{
       NotAPieceOfLettuce()
        .simultaneousGesture(TapGesture().onEnded{print("just a banana, not lettuce")})
    }
}

Tested with Xcode 13.4 / iOS 15.5

demo

You need to use the .simultaneousGesture on the gesture that does not get launched otherwise. In this case that would be the parent container.

// Child component
struct NotAPieceOfLettuce: View {
    var body: some View{
        Text("what am I?")
            .onTapGesture{print("I am not a piece of lettuce")}
    }
}

// Parent component, whos `onTapGesture` doesn't get called.
struct Banana: View {
    var body: some View{
        NotAPieceOfLettuce()
            .simultaneousGesture(
                TapGesture()
                    .onEnded { _ in
                        print("just a banana, not lettuce")
                    }
            )
    }
}

Paul Hudson article: https://www.hackingwithswift.com/quick-start/swiftui/how-to-make-two-gestures-recognize-at-the-same-time-using-simultaneousgesture

Related