3

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,567
  • 1
  • 14
  • 14

2 Answers2

7

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
    }
}

backup

Asperi
  • 173,274
  • 14
  • 284
  • 455
  • 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
1

You need to use this modifier:

.allowsHitTesting(false)
Bhargav Rao
  • 45,811
  • 27
  • 120
  • 136
  • 2
    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