Member-only story
SwiftUI Tutorial: Basic Animations
Understanding implicit and explicit animations

SwiftUI takes care of all the complexity in making effects by automatically animating any transitions that will happen. Done are the days of writing complicated code just to make simple animated transitions. The framework comes with enough built-in effects that can perform different animations.
In this tutorial, we will cover the basics of SwiftUI animations by understanding how to use implicit and explicit. But before anything else, make sure that you have an open project for this tutorial.
Implicit Animations
Uses a modifier called animation()
. By attaching the modifier to the desired views, SwiftUI will automatically render the animations based on specified animation type.
Let’s create a tappable heart animation that is popularly used on social media. What happens here is that the heart will turn red and scale larger when tapped. Begin by creating a heart from system image.
struct ContentView: View {
@State private var heartChange = false
var body: some View {
ZStack {
Image(systemName: heartChange ? "heart.fill" : "heart")
.font(.system(size: 100))
.foregroundColor(heartChange ? .red : .black)
.scaleEffect(heartChange ? 1.5 : 1.0)
} //ZStack
.onTapGesture {
self.heartChange.toggle()
}
} //body
} //ContentView
There are 2 parts in this code that needs to be discussed. First is the state variable that should be changing from false to true and vice versa. Then the .onTapGesture
(that’s why we have ZStack) will be responsible for changing the state using toggle()
.
If you run the application, tapping the heart will change the color and size of the object. But the object’s transition to another form is not animated. Because there’s one important thing that we didn’t include yet in this code. And that is the animation modifier that will handle the effects. Add this modifier just below scaleEffect
:
.animation(.default, value: heartChange)