在我的应用程序中,我水平拖动 aView
来设置模型对象的位置。我也可以向下拖动它并释放它以删除模型对象。当它被向下拖得足够远时,我通过改变它的外观来表示删除的可能性。问题是这种变化会中断DragGesture
. 我不明白为什么会这样。
下面的示例代码演示了该问题。您可以左右拖动浅蓝色框。如果你下拉,它会变成“光线”系统图像,但拖动会消失。
DragGesture
应用于ZStack
大小为 50x50 的。应该在状态变化中ZStack
继续存在,不是吗?为什么拖动手势会死?
struct ContentView: View {
var body: some View {
ZStack {
DraggableThing()
}.frame(width: 300, height: 300)
.border(Color.black, width: 1)
}
}
struct DraggableThing: View {
@State private var willDeleteIfDropped = false
@State private var xPosition: CGFloat = 150
var body: some View {
//Rectangle()
// .fill(willDeleteIfDropped ? Color.red : Color.blue.opacity(0.3))
ZStack {
if willDeleteIfDropped {
Image(systemName: "rays")
} else {
Rectangle().fill(Color.blue.opacity(0.3))
}
}
.frame(width: 50, height: 50)
.position(x: xPosition, y: 150)
.gesture(DragGesture()
.onChanged { val in
print("drag changed \(val.translation)")
self.xPosition = 150 + val.translation.width
self.willDeleteIfDropped = (val.translation.height > 25)
}
.onEnded { val in
print("drag ended")
self.xPosition = 150
}
)
}
}