Home > database >  Animate @GestureState on reset
Animate @GestureState on reset

Time:07-06

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)
    }
}

CodePudding user response:

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

  • Related