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
}
}