当 .onChanged 存在时,SwiftUI DragGesture 不会终止
我尝试在以下代码中使用 dragPiece
手势拖动视图(下面的 ZStack
)。如果我注释掉了 .onChanged 修饰符,则此代码可以正常工作,因为视图最终会重新定位。但是,当 .onChanged
未注释且处于活动状态时,拖动手势似乎会卡住,重复打印出相同的 width
和 height
值,并且.onEnded
修饰符永远不会被执行。这看起来应该很简单,所以显然我错过了一些东西。任何帮助将不胜感激。
struct PieceView: View {
var id: String
@State private var orientation: Int
@State private var dragOffset = CGSize.zero
@State var selected = false
var dragPiece: some Gesture {
DragGesture()
.onChanged { value in
dragOffset = value.translation
print("width: \(dragOffset.width), height: \(dragOffset.height)")
}
.onEnded{ value in
print("\(id) dragged")
dragOffset = value.translation
print("width: \(dragOffset.width), height: \(dragOffset.height)")
}
}
var body: some View {
ZStack {
Image(id + "\(orientation)")
Image("boardSquare")
.padding(0)
.gesture(dragPiece)
}
.offset(dragOffset)
}
init() {
id = ""
orientation = 0
}
init(id: String, orientation: Int = 0, gesture: String = "") {
self.id = id
self.orientation = orientation
}
}
I'm attempting to drag a view (the ZStack
below) using the dragPiece
gesture in the following code. If I have the .onChanged
modifier commented out, this code works fine, in the sense that the view ends up repositioned. But when .onChanged
is uncommented and active, the drag gesture seems to get stuck, repeatedly printing out the same width
and height
values, and the .onEnded
modifier is never executed. This seems like it should be straightforward, so clearly I'm missing something. Any help will be appreciated.
struct PieceView: View {
var id: String
@State private var orientation: Int
@State private var dragOffset = CGSize.zero
@State var selected = false
var dragPiece: some Gesture {
DragGesture()
.onChanged { value in
dragOffset = value.translation
print("width: \(dragOffset.width), height: \(dragOffset.height)")
}
.onEnded{ value in
print("\(id) dragged")
dragOffset = value.translation
print("width: \(dragOffset.width), height: \(dragOffset.height)")
}
}
var body: some View {
ZStack {
Image(id + "\(orientation)")
Image("boardSquare")
.padding(0)
.gesture(dragPiece)
}
.offset(dragOffset)
}
init() {
id = ""
orientation = 0
}
init(id: String, orientation: Int = 0, gesture: String = "") {
self.id = id
self.orientation = orientation
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
看来
.offset(dragOffset)
必须出现在.gesture(dragPiece)
之前。以下代码按预期工作:就我而言,这给我留下了一些其他 UI 设计问题,因为我希望手势应用于
Image("boardSquare")
但整个ZStack< /code> 被拖动。但这是一个单独的问题,至少现在我知道我当前的代码有什么问题。
It appears that
.offset(dragOffset)
must appear before.gesture(dragPiece)
. The following code works as expected:In my case, this leaves me with some other UI design issues, because I want the gesture to apply to
Image("boardSquare")
but the wholeZStack
to be dragged. But that's a separate issue, and at least now I know what the problem was with my current code.