I'm trying to create circles that can be dragged and dropped.
I am able to get it to work with just the first circle, however, anything after the first doesn't work.
Expected behaviour: Circle follows my cursor while dragging and lands on final position when drag ends
Actual behaviour: Circle follows my cursor's horizontal position, but not vertical position (vertical position is always significantly below my cursor)
ContentView.swift
import SwiftUI
struct ContentView: View {
var body: some View {
VStack(alignment: .center) {
ForEach(0..<5) { _ in
DraggableCircles()
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
struct DraggableCircles: View {
@State var dragAmount: CGPoint = CGPoint.zero
var body: some View {
Circle().fill(Color.red)
.frame(width: 50, height: 50)
.gesture(
DragGesture(coordinateSpace: .global).onChanged {action in
let location = action.location
let newWidth = location.x
let newHeight = location.y
let size = CGPoint(x: newWidth, y: newHeight)
self.dragAmount = size
}.onEnded{action in
let location = action.location
let newWidth = location.x
let newHeight = location.y
let size = CGPoint(x: newWidth, y: newHeight)
self.dragAmount = size
}
)
.position(x: dragAmount.x, y: dragAmount.y)
}
}
question from:
https://stackoverflow.com/questions/65868318/swiftui-drag-and-drop-circles 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…