Animatable
A type that describes how to animate a property of a view.
Declaration
protocol AnimatableOverview
When an animatable value changes inside a withAnimation(_:_:) block (or is affected by an animation(_:value:) modifier), SwiftUI reads the old and new animatableData values, then interpolates between them over successive frames using VectorArithmetic operations. The framework calls the animatableData setter on each frame, giving your type a chance to update any derived state.
Use the Animatable macro
To conform a type to the Animatable protocol, use the Animatable() macro to avoid writing the animatableData property by hand:
@Animatable
struct RingSegment: Shape {
var startAngle: Angle
var endAngle: Angle
// ...
}The macro inspects every stored property. Properties whose types conform to VectorArithmetic or Animatable are included in the synthesized animatableData. If a property cannot participate, the macro emits an error suggesting you mark it with AnimatableIgnored() or conform its type to VectorArithmetic or Animatable:
@Animatable
struct RingSegment: Shape {
var startAngle: Angle
var endAngle: Angle
@AnimatableIgnored var isOpaque: Bool
// ...
}Manual conformance for custom interpolation
Reach for a handwritten animatableData when the interpolated value needs custom logic that does not correspond one-to-one with a stored property, such as normalization, clamping, or driving a derived value.
Use AnimatableValues (26.0+ releases) to group multiple animated properties, or AnimatablePair on earlier deployment targets:
struct WaveShape: Shape {
var amplitude: CGFloat
var phase: CGFloat
var maxAmplitude: CGFloat
var animatableData:
AnimatableValues<CGFloat, CGFloat>
{
get {
AnimatableValues(amplitude, phase)
}
set {
amplitude = min(
max(newValue.value.0, 0),
maxAmplitude)
phase = newValue.value.1
.truncatingRemainder(
dividingBy: 2 * .pi)
}
}
// ...
}