Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Animate @GestureState on reset

I have a drag gesture, which has a Bool @GestureState that animates some changes in the view when the user is dragging. I’m using @GestureState to make sure the Bool is reset to false if the drag is interrupted or stops. Unfortunately, on the reset of @GestureState the Bool is reset without an animation. If I use @State and change the Bool manually onEnded and onChanged I can use withAnimation and the animations work, but since I need to be 100% certain that the Bool is false when the user isn’t dragging, I would prefer to use @GestureState. Or is it safe to use @State in this case? (if so, why would one ever use @GestureState?) This question seems to be having a similar problem, but there is no satisfactory answer.

My code:

struct SomeView: View {
    @GestureState var isNavigating: Bool = false
    var body: some View {
        
        let dragGesture = DragGesture(minimumDistance: 0)
            .updating($isNavigating, body: { dragValue, state, transaction in
                transaction.animation = .default
                state = true
            })
            .onChanged { _ in
                withAnimation {
                    //isNavigating = true this works when isNavigating is @State
                }
            }
            .onEnded { _ in
                withAnimation {
                    // isNavigating = false this works when isNavigating is @State
                }
            }
        
        VStack {
            Text("Hello World")
            if isNavigating {
                Text("Dragging")
            }
        }
        .gesture(dragGesture)
    }
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Add animation per value of gesture state, like

    VStack {
        Text("Hello World")
        if isNavigating {
            Text("Dragging")
        }
    }
    .animation(.default, value: isNavigating)   // << here !!
    .gesture(dragGesture)

Tested with Xcode 13.4 / iOS 15.5

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading