8

I am creating a tooltip system.

I want to dismiss the tooltip if the user touches anywhere outside the tooltip.

I would like it so that a touch outside the tooltip both dismisses the tooltip and activates any controls the user tapped on. (So you could have a tooltip open and still click a button outside the tooltip and have it activate on the first tap.)

To do this, I have an invisible view handling the tap gesture and dismissing the tooltip, but I do not know how to make SwiftUI not intercept and cancel the tap gestures. On the web, it's the equivalent of not calling event.stopPropagation() and event.preventDefault(), or calling super in touchesBegan: in UIKit.

Any ideas?

Wil Gieseler
  • 1,893
  • 1
  • 17
  • 18

2 Answers2

13

Here is a demo of possible approach. Tested with Xcode 11.4 / iOS 13.4

struct ContentView: View {
    var body: some View {
        VStack {
            Button("Button") { print("> button tapped")}
        }
        .frame(width: 200, height: 200)
        .contentShape(Rectangle())       // makes all area tappable
        .simultaneousGesture(TapGesture().onEnded({
             print(">>> tooltip area here")
        }))
        .border(Color.red)   // just for demo show area
    }
}
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Asperi
  • 228,894
  • 20
  • 464
  • 690
  • 1
    Tnx. You saved my day. I had a problem with PDFView and button over it which didn't accept touch event. – Vladimir Mar 14 '21 at 14:12
4

You need to use this modifier:

.allowsHitTesting(false)
Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
  • 3
    This does not answer my question. I need to allow hit testing in order to handle the tap gesture to dismiss the tooltip. But I also want my tap to affect views behind that view. – Wil Gieseler Apr 26 '21 at 23:34