问题描述
我有以下问题.
我有一个 View
在我想要拖动的 ScrollView
里面.现在,一切正常,发生拖动和滚动.但是,一旦我尝试同时执行这两项操作,dragOffset
似乎会保持不变,而不是重置到其初始位置.
I have a View
inside a ScrollView
that I want to drag.Now, everything works fine, the dragging occurs and the scrolling as well. But once I try to do both, the dragOffset
appears to stay, instead of resetting to its initial position.
更重要的是,DragGesture
的 onEnded
永远不会发生.如何阻止这种情况发生并将绿色 Rectangle
重置为其初始位置?
More so, onEnded
of the DragGesture
never happens. How can I stop this from happening and reset the green Rectangle
to its initial position?
拖动或滚动效果很好.
但每当我同时做这件事时,就会发生这种情况.
But whenever I do both, this happens.
struct ContentView: View {
@State private var dragOffset: CGSize = .zero
var body: some View {
ScrollView {
Rectangle()
.frame(width: UIScreen.main.bounds.size.width, height: 300)
.foregroundColor(.green)
.offset(x: dragOffset.width)
}
.gesture(DragGesture()
.onChanged { value in
dragOffset = value.translation
}
.onEnded { value in
dragOffset = .zero
}
)
.animation(.default)
}
}
谢谢!
推荐答案
解决方案是使用 .updating
和 GestureState
代替.无论出于何种原因取消手势后,它都会自动将偏移设置为其初始位置.
The solution is to use .updating
with GestureState
instead. It automatically sets the offset to its initial position, after the gesture got canceled for whatever reason.
这样,我们独立于调用 onEnded
将其设置为初始位置,这在您通过滚动取消手势时不会发生.
That way, we are independent of calling onEnded
to set it to its initial position which doesn't happen when you cancel the gesture by scrolling.
代码:
struct ContentView: View {
@GestureState private var dragOffset: CGSize = .zero
var body: some View {
ScrollView {
Rectangle()
.frame(width: UIScreen.main.bounds.size.width, height: 300)
.foregroundColor(.green)
.offset(x: dragOffset.width)
}
.gesture(DragGesture()
.updating($dragOffset) { value, state, transaction in
state = value.translation
}
)
.animation(.default)
}
}
注意:当然你仍然可以有一个 onChanged
和 onEnded
块,你只是不必将偏移量设置为 .zero
因为它是自动发生的.
Note: You can of course still have an onChanged
and onEnded
block, you just don't have to set the offset to .zero
any longer since it happens automatically.
如果您要在 ObservableObject
类中使用它并希望您的 dragOffset 被发布,那么 这里将是一个我找到的解决方案.
If you are to use it inside ObservableObject
class and want your dragOffset to be published, then here would be a solution I found.
这篇关于SwiftUI |如果被 ScrollView 取消,则不会调用 DragGestures onEnded的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!