SwiftUI拖动手势通过多点触摸冻结



我正试图在SwiftUI中拖动一个视图。

拖动非常有效,直到我把第二根手指放在屏幕上,然后拖动停止,两个代码块(onChangedonEnded(都没有被调用。

但是,当我再次开始用一根手指拖动时,它又开始工作了。

有什么办法可以解决这个问题吗?或者我错过了什么?

struct Pager: View {
func drag(geometry: GeometryProxy) -> some Gesture {
DragGesture()
.onChanged({ (value) in
//some code
})
.onEnded({ (value) in
//some code
})
}
var body: some View {
GeometryReader { (geometry) in
ZStack {
ForEach(self.items.indices.reversed(), id: .self) { index in
Card(index: index, item: self.items[index])
.offset(x: 0, y: self.offset(index: index, geometry: geometry))
.animation(.linear)
}
}
.background(Color.black)
.gesture(self.drag(geometry: geometry))
}
}
}

这种方法非常有用:

检测SwiftUI 中的拖动手势取消

所以基本上,你用捏和拖动来组成拖动手势;旋转手势(同时使用.组合(。

当捏或旋转被触发时,你可以用它来发出取消拖动手势的信号,并相应地更新你的状态

您可以使用与本文相同的解决方案,因为我相信这是相同的底层问题。该解决方案使用手势状态,该状态(如链接帖子中所述(是一个临时值,并在手势完成/中断时返回到其初始状态(0,0(。

当你使用手势状态时,你的代码应该是这样的(尽管你可能可以调整它来使用一个单独的拖动方法,就像在你的原始帖子中一样(:

struct Pager: View {
@GestureState private var dragPosition = CGSize.zero
var body: some View {
ZStack {
ForEach(self.items.indices.reversed(), id: .self) { index in
Card(index: index, item: self.items[index])
.offset(x: 0, y: self.dragPosition.height) // This will now map the y offset of the card to the dragPosition GestureState. If you want the x offset use self.dragPosition.width
.animation(.linear)
}
}
.background(Color.black)
.gesture(
DragGesture()
.updating($dragPosition) { (value, gestureState, transaction) in
gestureState = CGSize(width: value.location.x - value.startLocation.x, height: value.location.y - value.startLocation.y)
}
.onChanged { value in
print("I'm changing")
}
.onEnded { value in
print("I've ended")
}
)
}
}

最新更新