Adding Animation
December 29, 2023
- We can add an animation in SwiftUI, using
withAnimation()
- Let’s create a button and a rounded rectangle with following elements.
- Create a boolean variable
isAnimated - Now we can use ternary operators to change the value of elements.
- use @State to update the view.
- use .toggle() to change the boolean.
- We use
withAnimation()to provide animation feature in view. - inside the button function, we wrap the toggle with
withAnimation() withAnimation(Animation.default){isAnimated.toggle()}
- We can also change the offset value and give rotationEffect to rounded rectangle for dynamic animations.
.offset(y: isAnimated ? 150 : 0).rotationEffect(Angle(degrees: isAnimated ? 180 : 0))
- We can provide a delayed animation or repeating animation by adding
.delay(double)or.repeatCount()
use withAnimation(Animation.default) instead
In SwiftUI, animations can be added using withAnimation(). A button and a rounded rectangle can be created, with a boolean variable isAnimated used to change the value of elements. The withAnimation() function provides animation features in the view, and can be used to change the offset value and give rotation effects for dynamic animations. Delayed or repeating animations can be added using .delay(double) or .repeatCount(). Note that .animation() is not allowed in visionOS, use withAnimation(Animation.default) instead.