UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

SOLVED: Instantly reset state of animation.

Forums > SwiftUI

Given a view like this:

struct ContentView: View {
    @State private var percentAnimated: CGFloat = .zero

    var body: some View {
        VStack {
            Button("Reset") {
                percentAnimated = .zero
            }

            AnimatedView() {
                // does something with percentAnimated
            }
            .onAppear {
                percentAnimated = 1
            }
        }
    }
}

When the view appears, percentAnimated's state changes to 1 and any animation in body that uses this state begins animating. When I tap the button, the state reverts back to zero but the animations that use this state 'reverse' their animations.

Is there a way to instantly set the state back to zero and bring any view that uses this state back to it's original state? (i.e. don't 'reverse' the animation, start over)

3      

First, you can't attach onAppear to the body property; you have to attach it to something inside the body property.

Then try adjusting the id of the View component to get everything back to the starting value. Something like this:

struct ResetRect: View {
    @State private var sz: CGFloat = 80
    var body: some View {
        Rectangle().frame(width: sz, height: sz)
            .onAppear {
                withAnimation(Animation.easeInOut(duration: 2.5).repeatForever(autoreverses: true)) {
                    sz *= 2
                }
            }
    }
}

struct ContentView: View {
    @State private var percentAnimated: CGFloat = .zero
    @State private var viewID = 0

    var body: some View {
        ResetRect()
            .id(viewID)
        Button("Reset") {
            viewID += 1
        }
        //...
        .onAppear {
            percentAnimated = 1
        }

    }

}

Changing the id resets everything because it is technically creating a brand new View struct to replace the existing one rather than resetting it to the initial values.

3      

TAKE YOUR SKILLS TO THE NEXT LEVEL If you like Hacking with Swift, you'll love Hacking with Swift+ – it's my premium service where you can learn advanced Swift and SwiftUI, functional programming, algorithms, and more. Plus it comes with stacks of benefits, including monthly live streams, downloadable projects, a 20% discount on all books, and free gifts!

Find out more

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.