Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to disable user interaction on SwiftUI view?

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.

like image 440
chockenberry Avatar asked Sep 11 '19 20:09

chockenberry


5 Answers

There is a modifier on View to disable or enable user interaction:

disabled(_ disabled: Bool)

like image 32
LuLuGaGa Avatar answered Nov 16 '22 14:11

LuLuGaGa


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)
}
like image 122
MihaiL Avatar answered Nov 16 '22 14:11

MihaiL


You want to make sure you fill your view with some color, except Clear color (you can always change opacity). I've also added blur to hide elements. Here's what worked for me:

SwiftUI:

ZStack{
    SomeView().blur(radius: 12)
    Rectangle()
        .fill(Color.white.opacity(0))
        .allowsHitTesting(false)
}

Another way to disable user interactions like scroll or button taps, but attach an action to user taps (for example a message to users that this feature is coming or behind a paywall):

SwiftUI:

VStack{
    SomeView().blur(radius: 12)
}
.contentShape(Rectangle())
.onTapGesture {
    print("No access!")
}
like image 27
Repose Avatar answered Nov 16 '22 15:11

Repose


SwiftUI 2.0

 ZStack {

    // Your Stack to Disable User Interaction

}.disabled(showLoadingIndicator)
like image 10
Threadripper Avatar answered Nov 16 '22 16:11

Threadripper


This is most likely a bug in SwiftUI, but the workaround for this problem was to remove a .border() that I had put on the Text view for bounds debugging.

like image 4
chockenberry Avatar answered Nov 16 '22 14:11

chockenberry