Search code examples
swiftswiftui

How to prevent a circle animation from reversing?


My circle is a countdown. The variable pct is a changing variable that runs from 0.0 to about 0.99. the problem is that as soon as the variable is 1.0 it is animated backwards. how can i get it to start at 0 again?

enter image description here

struct ActivityCircle : View {
    let color: UIColor
    let pct: CGFloat
    
    @State var progress: CGFloat = 0.0
    
    
    var body: some View {
        Circle()
            .trim(from: 0, to: progress)
            .rotation(Angle(degrees: -90))
            .stroke(style: StrokeStyle(lineWidth: 13, lineCap: .round, lineJoin: .round))
            .foregroundColor(Color(color))
        // .animation(Animation.linear(duration: 1), value: progress)
            .onAppear{
                print("circle appears")
                //                                withAnimation(.linear(duration: 20)){
                //                                    progress = 1
                //                                }
                
            }
            .onChange(of: pct)  { oldValue, newValue in
                print("Old value is \(oldValue)")
                print("New value is \(newValue)")
                withAnimation(.linear(duration: 1.0)) {
                    
                    if(newValue == 0){
                        progress = 1.0
                    } else {
                        progress = newValue
                    }
                }
                
            }
        
    }
}

Solution

  • Have a look at this answer: https://www.hackingwithswift.com/forums/swiftui/instantly-reset-state-of-animation/4494

    changing the id of the component will reset the view