Recently while working on a project, we ran into an issue where we had two views stacked on top of each other but we wanted view in the back to respond to the tap events.
Upon researching further, we found that SwiftUI provides allowsHitTesting modifier for just this purpose.
Let’s take a look at an example. We will create a view with Button which will update text in Text view. Button’sinteraction will be controlled by a Toggle.
struct DevTechieUserInteractionExample: View {
@State private var text = "Some text"
@State private var interactionEnabled = true
var body: some View {
VStack(spacing: 20) {
VStack {
Text("DevTechie")
.font(.largeTitle)
Text(text)
Button("This is a button") {
text = "Random number \(Int.random(in: 0...1000))"
}
.buttonStyle(.borderedProminent)
.allowsHitTesting(interactionEnabled)
Toggle("Toggle button interaction", isOn: $interactionEnabled)
}
.padding()
}
}
}
Let’s update view to include two buttons in ZStack and we will toggle their interactions with allowsHitTesting using two toggles.
struct DevTechieUserInteractionExample: View {
@State private var text = "Some text"
@State private var innerButtonInteraction = true
@State private var outterButtonInteraction = true
var body: some View {
VStack(spacing: 20) {
VStack {
Text("DevTechie")
.font(.largeTitle)
Text(text)
ZStack {
Button {
text = "Random number \(Int.random(in: 0...1000))"
} label: {
Circle()
.fill(.orange.gradient)
.frame(width: 200, height: 200)
}
.allowsHitTesting(outterButtonInteraction)Button("Button") {
text = "Random number \(Int.random(in: 0...1000))"
}
.foregroundStyle(Color.blue)
.buttonStyle(.borderedProminent)
.allowsHitTesting(innerButtonInteraction)
}
Toggle("Inner button interaction", isOn: $innerButtonInteraction)Toggle("Outter button interaction", isOn: $outterButtonInteraction)}
.padding()
}
}
}
With that we have reached the end of this article. Thank you once again for reading. Don’t forget to 👏 and follow 😍. Also subscribe our newsletter at https://www.devtechie.com