0

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)
    }
}
cliffT
  • 3
  • 2

1 Answers1

1

Use ZStack and gesture sequenced.

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)
            }
        
        let dragGesture = DragGesture(minimumDistance: 0, coordinateSpace: .global)
            .onChanged { value in
                self.dragLocation = value.location
            }
        
        ZStack { //< Here
            ForEach(points, id: \.x) {point in
                CreateCircle(location: point)
            }
        }
        .background(Color.black
                        .scaledToFill())
        .ignoresSafeArea()
        .gesture(dragGesture.sequenced(before: tapDetector)) //<-- Here
    }
}

enter image description here

Raja Kishan
  • 16,767
  • 2
  • 26
  • 52