< How to control the tappable area of a view using contentShape() | How to detect the location of a tap inside a view > |
Updated for Xcode 14.2
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)
}
Download this as an Xcode project
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.
SPONSORED Play is the first native iOS design tool created for designers and engineers. You can install Play for iOS and iPad today and sign up to check out the Beta of our macOS app with SwiftUI code export. We're also hiring engineers!
Sponsor Hacking with Swift and reach the world's largest Swift community!
Link copied to your pasteboard.