Greetings, traveler!
Sometimes, it is necessary to disable the ability to interact with a view using gestures. In UIKit, we used an isUserInteractionEnabled property of the UIView to prevent users from interacting with a view. In SwiftUI, we can use alternative techniques for this purpose. Two instance methods can fit our needs.
disabled(_:)
This method will add a condition for controlling whether users can interact with the view. But let’s look at an example where you put one view over another. The view that is placed on top can be interactable in some cases, but not in this one. So you can disable interaction with it via the disabled method. But this will also prevent you from interacting with the view on the bottom of your stack.
struct ContentView: View {
var body: some View {
VStack {
Image(systemName: "globe")
.imageScale(.large)
.foregroundStyle(.tint)
Text("Hello, world!")
}
.frame(maxWidth: .infinity)
.onTapGesture {
print("Tapped")
}
.overlay {
ZStack {
Rectangle()
.fill(Color.green.opacity(0.2))
Text("Toast")
}
.disabled(true) // ❗️ Not allow you to interact with the VStack using gestures.
}
}
}
For such cases, another SwiftUI method is available.
allowsHitTesting(_:)
This instance method determines whether the view participates in hit test operations. You can provide the ‘false’ value through its parameters, allowing you to interact with other views via gestures.
struct ContentView: View {
var body: some View {
VStack {
Image(systemName: "globe")
.imageScale(.large)
.foregroundStyle(.tint)
Text("Hello, world!")
}
.frame(maxWidth: .infinity)
.onTapGesture {
print("Tapped")
}
.overlay {
ZStack {
Rectangle()
.fill(Color.green.opacity(0.2))
Text("Toast")
}
.allowsTightening(false) // ❗️ Allow you to interact with the VStack using gestures.
}
}
}
Conclusion
SwiftUI has not yet reached the level of flexibility of UIKit, but with each new release, it is getting closer.