How to disable user interaction on SwiftUI view?

chockenberry picture chockenberry · Sep 11, 2019 · Viewed 13.5k times · Source

Let's say I have a SwiftUI view hierarchy that looks like this:

ZStack() {
    ScrollView {
        ...
    }
    Text("Hello.")
}

The Text view blocks touch events from reaching the underlying ScrollView.

With UIKit, I'd use something like .isUserInteractionEnabled to control this, but I can't find any way to do this with SwiftUI.

I've tried adding a Gesture with a GestureMask of .none on the text view, but that doesn't seem to work.

I hope I'm missing something obvious here, because I need to put some status information on top of the scroll view.

Answer

MihaiL picture MihaiL · Nov 18, 2019

What about using the .allowsHitTesting()?

https://developer.apple.com/documentation/swiftui/image/3269586-allowshittesting

From my understanding it should pass the gesture to the view behind if it's disabled.

ZStack() {
    ScrollView {
        ...
    }
    Text("Hello.").allowsHitTesting(false)
}