SwiftUI_visionOS_Note

Adding Animation

Dec 29, 2023

December 29, 2023

 
Callout icon'
withAnimation()
 
  • We can add an animation in SwiftUI, using withAnimation()
 
  1. Let’s create a button and a rounded rectangle with following elements.
 
 
  1. Create a boolean variable isAnimated
    1. Now we can use ternary operators to change the value of elements.
    2. use @State to update the view.
    3. use .toggle() to change the boolean.
    4.  
 
  1. We use withAnimation() to provide animation feature in view.
    1. inside the button function, we wrap the toggle with withAnimation()
      1. withAnimation(Animation.default){isAnimated.toggle()}
 
 
  1. We can also change the offset value and give rotationEffect to rounded rectangle for dynamic animations.
    1. .offset(y: isAnimated ? 150 : 0)
    2. .rotationEffect(Angle(degrees: isAnimated ? 180 : 0))
 
 
  1. We can provide a delayed animation or repeating animation by adding .delay(double) or .repeatCount()
 
 
 
Callout icon'
.animation() ← isn’t allowed in visionOS.
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.

You might also like

BlogPro logo
Made with BlogPro