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

Day 45: When do we need to use animatableData for animation?

Forums > 100 Days of SwiftUI

Day 45 introduced the animatableData and AnimatablePair to animate custom shapes. This fixes the problem that withAnimation { ... } does not actually animate the shape change.

But in other scenarios, we CAN animate changes to a state variable using just withAnimation { ... }, e.g., in the following snippet:

struct ContentView: View {
    @State private var stroke = 50.0

    var body: some View {
        Circle()
            .stroke(style: StrokeStyle(lineWidth: stroke))
            .frame(width: 200, height: 200)
            .onTapGesture {
                withAnimation {
                    stroke = Double.random(in: 10..<90)
                }
            }
    }
}

I don't quite understand the fundamental difference between these two cases. So my question is, when do we actually need to use the animatableData? Thanks in advance!

===

P.S. I've got another example, here I have to define animatableData: AnimatablePair for the insetAmountLeft/Right for the animation to work, but the foregroundColor animates just fine. Why? Is it because the insetAmountLeft/Right are internal definitions within Trapezoid, instead of a SwiftUI built-in property like .foregroundColor?

struct ContentView: View {
    @State private var insetAmountLeft = 50.0
    @State private var insetAmountRight = 50.0
    @State private var colorAmount = 0.5

    var body: some View {
        Trapezoid(insetAmountLeft: insetAmountLeft, insetAmountRight: insetAmountRight)
            .frame(width: 200, height: 100)
            .onTapGesture {
                withAnimation {
                    insetAmountLeft = Double.random(in: 10...90)
                    insetAmountRight = Double.random(in: 10...90)
                    colorAmount = Double.random(in: 0.1...0.9)
                }
            }
            .foregroundColor(Color.init(white: colorAmount))
    }
}

3      

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.