Follow Every Drag Change with SwiftUI

Dragging objects around on a screen is a common interaction in many apps, and with SwiftUI, it’s easy to create an interactive experience that allows users to follow every drag change for a circle around the screen with their finger. However, the challenge lies in making the circle smoothly follow the user’s finger as they drag it around.

To achieve this, we will use SwiftUI’s built-in gesture recognition capabilities and the @State property wrapper to store and update the circle’s position. Here’s how it’s done:

struct ContentView: View {
    @State private var circlePosition = CGPoint(x: 100, y: 100)
    
    var body: some View {
        Circle()
            .fill(Color.blue)
            .frame(width: 100, height: 100)
            .position(circlePosition)
            .gesture(
                DragGesture()
                    .onChanged { gesture in
                        circlePosition = gesture.location
                    }
            )
    }
}

We are adding a DragGesture to the Circle view and updating the circlePosition variable with the gesture’s location in the onChanged closure.

When you run this code, you’ll see the circle follow every drag change:

Follow Every Drag Change

Leave a Reply

Your email address will not be published. Required fields are marked *