Skip to main content

How to disable taps for a view using allowsHitTesting()

About 2 minSwiftSwiftUIArticle(s)bloghackingwithswift.comcrashcourseswiftswiftuixcodeappstore

How to disable taps for a view using allowsHitTesting() 관련

SwiftUI by Example

Back to Home

How to disable taps for a view using allowsHitTesting() | SwiftUI by Example

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)
}

Download this as an Xcode projectopen in new window

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.

Similar solutions…
How to disable autocorrect in a TextField | SwiftUI by Example

How to disable autocorrect in a TextField
How to disable the overlay color for images inside Button and NavigationLink | SwiftUI by Example

How to disable the overlay color for images inside Button and NavigationLink
How to disable ScrollView clipping so contents overflow | SwiftUI by Example

How to disable ScrollView clipping so contents overflow
SwiftUI tips and tricks | SwiftUI by Example

SwiftUI tips and tricks
How to convert a SwiftUI view to an image | SwiftUI by Example

How to convert a SwiftUI view to an image

이찬희 (MarkiiimarK)
Never Stop Learning.