TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

SwiftUI animation "rollback" issue

Forums > SwiftUI

I have an animation depending on a range. When the end is reached the value is reseted to 0. Unfortunately I get a "rollback" animation which looks very bad but I have no idea how to handle it. Here is a sample code:

import SwiftUI

let clockTimer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()

struct ContentView: View {
    static func getDate(d : Date) -> Int {
        let dc = Calendar.current.dateComponents([.second], from: d)
        guard let s = dc.second else {
            fatalError("Can't get value!")
        }
        return s
    }

    @State var s = ContentView.getDate(d: Date())
    var body: some View {
        ZStack {
            Rectangle()
                .fill(.white)
                .frame(width: 200.0, height: 200.0)
            Rectangle()
                .fill(.red)
                .frame(width: 200.0/2.0-10.0, height: 1.5)
                .offset(CGSize(width: 50, height: 0))
                .rotationEffect(Angle(degrees: 360.0 / 60.0 * Double(s) - 90.0))
                .animation(.smooth, value: s)
        }
        .onReceive(clockTimer) { currentDate in
            s = ContentView.getDate(d: currentDate)
        }
    }
}

#Preview {
    ContentView()
}

Any clue how to solve this issue?

2      

It look like a second hand! You might want to look at Remaking the clock. This is a HWS+ so you might want to try the trail to look at it.

2      

Hacking with Swift is sponsored by RevenueCat.

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

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

Reply to this topic…

You need to create an account or log in to reply.

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.