How can I update the location X for offset in exact tap point for a view in SwiftUI?

Viewed 220

I am trying to update my Rec offset with drag Gesture of this Rec, I already coded in this way that the Rec start moving itself depending on drag and follow the drag as I coded, the problem that I get with this is it get centered itself always and I can not drag Rec out of screen, my goal is coding in way that offset start working with inter location of tag and it become the source for offset, now the source is center, which I like to be dynamic and be flexible as tap on Rec. How I should code this? enter image description here

    struct ContentView: View {
    

    @State var locationX: CGFloat = .zero
    let widthOfRec: CGFloat = 200
    
    var body: some View {

        Rectangle()
            .fill(Color.red)
            .frame(width: widthOfRec)
            .border(Color.black)
            .offset(x: locationX - widthOfRec/2)
            .gesture( DragGesture().onChanged { value in locationX = value.location.x })
        
        
        
        
    }
}
1 Answers

If I correctly understood your goal you need to use GestureState. The gesture state has temporary value which reset back to initial once gesture finished.

Here is a demo of possible solution. Prepared with Xcode 12.1 / iOS 14.1

demo

struct ContentView: View {
    
    @State var locationX: CGFloat = .zero
    @GestureState private var translationX = CGFloat.zero

    let widthOfRec: CGFloat = 200
    
    var body: some View {

        Rectangle()
            .fill(Color.red)
            .frame(width: widthOfRec)
            .border(Color.black)
            .offset(x: locationX + translationX)
            .gesture(
                DragGesture().updating($translationX) { value, state, _ in
                    state = value.translation.width
                }.onEnded { value in
                    locationX += value.translation.width
                }
            )
    }
}
Related