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