I want to animate a Slider
whenever its value
changes with a custom animation (with a custom duration). But somehow it doesn't work. No matter what animation
I specify, it always uses the same (very short) animation that is almost not noticeable.
Here's a minimal code example:
struct SliderView: View {
@State var value: Float = 0
var body: some View {
VStack {
Slider(value: $value)
.animation(.linear(duration: 3), value: value) // ← here
Button("Toggle") {
value = value < 0.5 ? 1 : 0
}
}
.frame(width: 300, height: 200)
.padding(16)
}
}
What am I doing wrong?
Note 1: Without the animation
modifier, I get no animation at all and the knob immediately jumps to its new position. With the modifier, it animates but it doesn't seem to respect the concrete animation I specify.
Note 2: I know that I could use an explicit animation and wrap the change in a withAnimation
closure. But even if that worked, it's not an option for me because the in my concrete case, the value
is not a @State
but a @Binding
and is thus set externally from a view model that should not know anything about SwiftUI.