Animations are very important when it comes to user experience. The look and feel of an app are improved by well-done animations.
Basic animations are easy to implement in SwiftUI using the
animation modifier. Every time the value that we're observing changes, SwiftUI will automatically animate any changes that occur to that view once the
animation modifier is applied. This modifier can be used to animate a view’s colour, opacity, rotation, size, and other properties which follow the
animation modifier takes two inputs, the animation timing and the value of the property to animate. We can define the duration of the animation, delay and type of timing curve to use through the timing property in the
To scale a view in SwiftUI, we use the
scaleEffect modifier. We can animate the scale effect by simply adding the animation modifier to the view with some configurations and SwiftUI will take care of the rest.
One thing to note about the animation modifier is that, as the order of modifier is important in SwiftUI, only the changes added before the animation modifier will be animated.
Apart from the animation modifier, we can also use the
withAnimation closure. All the changes to the state variables inside the
withAnimation closure will be animated. The advantage of using the
withAnimation closure is that it is not attached to a view and multiple state variables can be modified inside the same closure.
To animate the same above example using
withAnimation. We will remove the animation modifier, and modify the
setScale function as below.
Using the above methods we can animate any property which follows the Animatable protocol such as offset, opacity, colour, and scale. In the coming blogs, we will look into more advanced examples of animation using SwiftUI.