I am trying to create a system where clicking on a point within the screen creates a circle at the specified point.
However, i end up with every tap creating a circle at the same x-axis position all the time with different vertical positions.
Please see gif below for visualization of the current situation.
https://i.stack.imgur.com/KJ9yz.gif
Simplified code below:
import SwiftUI
struct ContentView: View {
@State var points: [CGPoint] = [CGPoint.zero]
@State var dragLocation: CGPoint?
@State var tapLocation: CGPoint?
var body: some View {
let tapDetector = TapGesture()
.onEnded {
tapLocation = dragLocation
guard let point = tapLocation else {
return
}
points.append(point)
}.simultaneously(with:
DragGesture(minimumDistance: 0, coordinateSpace: .global).onChanged { value in
self.dragLocation = value.location
})
VStack {
ForEach(points, id: .x) {point in
CreateCircle(location: point)
}
}
.background(Color.black
.scaledToFill())
.ignoresSafeArea()
.gesture(tapDetector)
}
}
struct CreateCircle: View {
@State private var currentLocation: CGPoint = CGPoint(x: 100, y: 100)
init(location: CGPoint) {
currentLocation = location
}
var body: some View {
return Circle().fill(Color.red)
.frame(width: 50, height: 50)
.position(currentLocation)
}
}
question from:
https://stackoverflow.com/questions/65870056/swiftui-adding-shape-at-specified-position-on-tap 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…