< 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.
SAVE 50% To celebrate WWDC23, all our books and bundles are half price, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.
Link copied to your pasteboard.