< How to control the tappable area of a view using contentShape() | What’s the difference between @ObservedObject, @State, and @EnvironmentObject? > |
Updated for Xcode 12.5
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(Color.white)
Rectangle()
.fill(Color.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.
SPONSORED Building and maintaining in-app subscription infrastructure is hard. Luckily there's a better way. With RevenueCat, you can implement subscriptions for your app in hours, not months, so you can get back to building your app.
Sponsor Hacking with Swift and reach the world's largest Swift community!
Link copied to your pasteboard.