Animation is a critical part of iOS user interface. Using the right animation at the right place will improve user experience. In SwiftUI you can add animations to a view or to view’s state. In this post you will see,
- How to add animation to individual view
- How to add animation effects for state change
- How to add effects through view transition
How to add animations to individual views?
With the help of the animate(_:)
modifier you can add animation to a view. A view’s color, opacity, rotation, size and other properties are animatable.
Lets create a button and try animating them on rotation and size change.
Let’s turn animation for buttons rotation by adding, animation(.easeInOut)
Add another animatable change by making the button larger when the buttons state value changes.
You can turn off animation for specific property by adding the .animation(nil)
just below the animatable property.
Add animations to state changes
Let’s apply animations when we toggle the “showGraph” state. Here, toggling showGraph state will display a view accordingly. Lets wrap showGraph.toggle()
with a call to the withAnimation
function.
Let’s add two seconds long basic animation in the withAnimation
function.
Adding transitions
Lets add on-and-off fading transition by adding transition(_:)
modifier to the view,
Now the view will appear and disappear by sliding in and out.
Next up let’s create a transition static property for “AnyTransition”. This keeps our code clean when we expand with transition. We can use the dot notation to use our custom transition.
Let’s add our custom transition moveAndFade
with the help of dot notation.
And now we are going to use move transition so that the view moves in and out from the same edge.
Now that you know how basic animation works,You can tackle some complex animations from here. Hope you enjoyed reading this post. Will meet you with another one soon!