I want to drag one view within a ZStack. In this example code the Toolbar has a blue draggable area. It should move Toolbar around the screen, by setting the offset. Instead, it goes into an infinite loop. How can it be fixed to drag correctly?
It prints the following eternally:
changed (36.5, 27.0)
changed (0.0, 0.0)
extension CGPoint {
func toSize() -> CGSize { .init(width:x, height:y) }
}
struct ContentView: View {
@State var offset: CGSize = .zero
var body: some View {
ZStack(alignment: .topLeading) {
Toolbar(dragOffset: $offset)
.offset(offset)
Text(verbatim: "Offset: \(offset)")
.frame(maxWidth: .infinity, maxHeight: .infinity)
}
}
}
struct Toolbar: View {
@Binding var dragOffset: CGSize
var body: some View {
HStack {
Color.blue.frame(width: 40, height: 40)
.gesture(drag)
Color.green.frame(width: 40, height: 40)
Color.red.frame(width: 40, height: 40)
}
}
var drag: some Gesture {
DragGesture()
.onChanged { value in
print("changed \(value.location)")
dragOffset = value.location.toSize()
}
.onEnded { value in
print("ended")
}
}
}