< 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 13.3
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 Fernando's book will guide you in fixing bugs in three real, open-source, downloadable apps from the App Store. Learn applied programming fundamentals by refactoring real code from published apps. Hacking with Swift readers get a $10 discount!
Sponsor Hacking with Swift and reach the world's largest Swift community!
Link copied to your pasteboard.