How To Ignore Tap In SwiftUI

Tapping is a basic thing when you want to give users the option to click on something.

Let’s say you have two views embedded in ZStack.

ZStack {
    
Color.blue
    
    .ignoresSafeArea()
    
    .onTapGesture(perform: {
    
        print(“Background tapped!”)
    
    })
    
Rectangle()
    
    .frame(width: 100, height: 100)
    
    .onTapGesture(perform: {
    
        print(“Rectangle tapped!”)
    })
}}

When you tap on the blue background you will receive log:

Background tapped!

When you tap on Rectangle then you will receive:

Rectangle tapped!

But what if you want to ignore tap on Rectangle and pass it to the background?

There is allowsHitTesting view modifier. You need to put there “false” value to pass tap.

.allowsHitTesting(false)

Now, when you tap anywhere you’ll always tap on the background.