How to disable taps for a view using allowsHitTesting()
How to disable taps for a view using allowsHitTesting() êŽë š
Updated for Xcode 15
SwiftUI lets us stop a view from receiving any kind of taps using the allowsHitTesting()
modifier. If hit testing is disallowed for a view, any taps automatically continue through the view on to whatever is behind it.
To demonstrate this, here's a ZStack
containing a translucent rectangle with a button underneath:
ZStack {
Button("Tap Me") {
print("Button was tapped")
}
.frame(width: 100, height: 100)
.background(.gray)
Rectangle()
.fill(.red.opacity(0.2))
.frame(width: 300, height: 300)
.clipShape(Circle())
.allowsHitTesting(false)
}
Even though the rectangle is on top of the button, it has allowsHitTesting(false)
â any taps on the rectangle won't be trapped by the rectangle, but instead passed through to the button below.
This kind of effect is useful for when you want to highlight one view with another â the red circle above might be part of a tutorial saying âTap here to get startedâ, and that wouldn't work if the circle itself caught the tap.