问题
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.
回答1:
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)
}
回答2:
There is a modifier on View to disable or enable user interaction:
disabled(_ disabled: Bool)
回答3:
You wanna 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!")
}
回答4:
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.
回答5:
Nothing worked for me, the gradient overlay is preventing the user to scroll but they can tap. So with .allowsHitTesting(false)
, I decided to make my own gradientView implementing UIViewRepresentable
and in the update function I did the following.
func updateUIView(_ uiView: UIView, context: UIViewRepresentableContext<MyCustomGradientView>) {
uiView.isUserInteractionEnabled = false
uiView.subviews.forEach({
$0.isUserInteractionEnabled = false
})
// This did the trick
uiView.superview?.isUserInteractionEnabled = false
}
来源:https://stackoverflow.com/questions/57896392/how-to-disable-user-interaction-on-swiftui-view