Scroll and translation conflict in SwiftUI

Viewed 174

I have a simple Circle, which is moveable on screen and it is inside of a ScrollView, when I am trying to move the circle vertically it get conflicted with scrolling function of ScrollView, it has to be a easy way to solve this since I never had this issue before, need help to solve it, thanks for help.



update: the Answer that pawello2222 gave solved my another problem that I did not asked for but I know it is there, if you try move an object in normal situation, you would be notice a glitch or kind of delay happen after tap down and drag, it turn is out all is solvable with minimumDistance: 0 thanks to pawello2222, in the fact there is no delay or animation glitch it is because of minimumDistance! So simple thing but with big role in game!



struct ContentView: View {
    var body: some View {
        ScrollView {
            CircleView()
        }
    }
}

struct CircleView: View {
    @State private var location: CGSize = CGSize()
    @GestureState private var translation: CGSize = CGSize()

    var body: some View {
        Circle()
            .fill()
            .frame(width: 100, height: 100, alignment: .center)
            .position(x: location.width + translation.width + 100, y: location.height + translation.height + 100)
            .gesture(DragGesture()
                .updating($translation) { value, state, _ in
                    state = value.translation
                }
                .onEnded { value in
                    location = CGSize(width: location.width + value.translation.width, height: location.height + value.translation.height)
                })
    }
}

enter image description here

1 Answers

By default the minumumDistance of the DragGesture is set to 10. From the documentation:

public init(minimumDistance: CGFloat = 10, coordinateSpace: CoordinateSpace = .local)

You need to explicitly set it to 0, so the scroll view won't take precedence:

Circle()
    .fill()
    .frame(width: 100, height: 100, alignment: .center)
    .position(x: location.width + translation.width + 100, y: location.height + translation.height + 100)
    .gesture(DragGesture(minimumDistance: 0) // <- add here
        .updating($translation) { value, state, _ in
            state = value.translation
        }
        .onEnded { value in
            location = CGSize(width: location.width + value.translation.width, height: location.height + value.translation.height)
        })
Related