How to start the gesture on the last updated position on SwiftUI?

Viewed 67

I'm having an issue that I can't figure out. I can't seem to figure out how to start the gesture where my last gesture position ended.

import SwiftUI

struct TestView: View {
    @State var xPosition: CGFloat = 50
    @State var yPosition: CGFloat = 50
    var body: some View {
        VStack{
            Circle()
                .frame(width: 100, height: 100)
                .position(x: xPosition, y: yPosition)
                .gesture(DragGesture()
                    .onChanged{gesture in
                        xPosition = gesture.translation.width
                        yPosition = gesture.translation.height
                    }
                    .onEnded{gesture in
                        xPosition = gesture.translation.width
                        yPosition = gesture.translation.height
                                
                    }
                )
        }
    }
}

struct TestView_Previews: PreviewProvider {
    static var previews: some View {
        TestView()
    }
}

This is the code, let say I make a gesture and move my circle to any given position (works great) but when I try dragging it again the gesture start again from the first position (50,50). is there a way to fix it that with GestureState or updating or anything else?

Thanks for taking the time to help me out on this one.

1 Answers

The translation is a relative location (equivalent to location.{x,y} - startLocation.{x,y}).

You should store the position instead, i.e.

struct TestView: View {
    @State var position: CGPoint = CGPoint(x: 50, y: 50)

    var body: some View {
        VStack{
            Circle()
                .frame(width: 100, height: 100)
                .position(position)
                .gesture(
                    DragGesture()
                        .onChanged { gesture in
                            position = gesture.location
                        }
                        .onEnded { gesture in
                            position = gesture.location
                        }
                )
        }
    }
}
Related