I was messing with Swift UI's linear animation techniques and noticed that, contrary to my expectations, increasing the duration does not seem to make the animation happen more slowly. Is this intentional? If so, how do I then make slower animations?
Sample code:
struct ButtonView: View {
@State var show: Bool = false
var body: some View {
ZStack{
if show {
withAnimation(.linear(duration: 50)) {
CollapsibleView()
}
}
}
Button(action: { show = !show }) {
Text("Press Me")
}
}
}
struct CollapsibleView: View {
var body: some View {
VStack {
Text("Text 1")
Text("Text 2")
Text("Text 3")
}
}
}
@main
struct app: App {
var body: some Scene {
WindowGroup {
ButtonView()
}
}
}
Try changing the duration parameter and see if you can notice slower animations. I went as high as 5000 (I assume this is measured in seconds?) and it was still animating at seemingly the same speed.
CodePudding user response:
You've placed the withAnimation
in the view hierarchy. Where you actually want it is in the Button
's action:
struct ButtonView: View {
@State var show: Bool = false
var body: some View {
ZStack{
if show {
CollapsibleView()
}
}
Button(action: {
withAnimation(.linear(duration: 10)) {
show.toggle()
}
}) {
Text("Press Me")
}
}
}
Alternately, you could use .animation
on the ZStack
:
struct ButtonView: View {
@State var show: Bool = false
var body: some View {
ZStack{
if show {
CollapsibleView()
}
}
.animation(.linear(duration: 10), value: show)
Button(action: {
show.toggle()
}) {
Text("Press Me")
}
}
}