UPDATE 1: I wrote the response below; then continued testing. Seems no matter what value I enter for duration, the change happens immediately. Now I am confused. Apologize for posting an answer that doesn't work. Ooooof.
UPDATE 2: Seems that adding the animation to the Form
works. Change the duration to 5 seconds and run in a simulator with the debug flag Slow Animations.
I agree with you, this still doesn't look right.
Original Post
Nice! +1 for not naming your view "ContentView".
I try to think of animations as a "before" and "after" snapshots of a view. Think of your kitchen "before" cooking a big meal, and the state of your kitchen "after" cooking a big meal. The before and after states are marked by the variable, isMealDone.
When isMealDone
changes from false
to true
we take a snapshot of the kitchen's final state. SwiftUI then produces all the frames inbetween.
You want to animate the kitchen, but in your code it looks like you're animating the toggle (the light switch).
Also, the animation() method has been deprecated. It works now, but in future releases it won't. The new method is .animation( animation, value:).
In short this modifier will animate the view you attach it to, using the animation you specify (.default, .easeIn, etc). Plus it will execute this animation when the specified value changes. SwiftUI will look at the state before the value changes and after the value changes, and SwiftUI will generate all the inbetween frames for you.
struct TestForm: View {
@State var sectionActive = false
var body: some View {
Form {
Section (header: Text("Section 1")) {
Toggle("Activate Section", isOn: $sectionActive)
if sectionActive {
List {
Text("Item 1")
Text("Item 2")
Text("Item 3")
}
}
}
}
// Add the animation to the Form
.animation(.easeOut(duration: 2.0), value: sectionActive) // Test in simulator with Slow Animations on.
}
}