Animate a View's Opacity in SwiftUI
Written by Team Kodeco
Animations can be used to significantly improve the look and feel of an app. In SwiftUI, animating the opacity of a view is a straightforward process. The opacity of a view can be thought of as a measure of its transparency, with an opacity of 0 meaning fully transparent and an opacity of 1 meaning fully opaque.
To animate a view’s opacity, start by creating a state variable to keep track of the current opacity value. You can then incorporate this value into the view’s body, using the opacity
modifier. Finally, use an animation modifier to specify the duration and timing of the animation.
struct ContentView: View {
@State private var opacity: Double = 0.0
var body: some View {
VStack {
Text("Hello, SwiftUI!")
.opacity(opacity)
.font(.largeTitle)
.padding()
Button(opacity == 0.0 ? "Fade In" : "Fade Out") {
withAnimation(.easeInOut(duration: 2)) {
opacity = opacity == 0.0 ? 1.0 : 0.0
}
}
}
}
}
Your preview should look like this after you tap Fade In:
In this example, a Text
view starts with an opacity of 0.0
, meaning it will initially appear invisible. Following this, a Button
is created that, when tapped, triggers an animation sequence.
This animation sequence is defined within a withAnimation
block, which is a SwiftUI function that applies an animation to any state changes that occur within its closure. In this block, the duration of the animation and the easing curve (a function that dictates the speed at which the animation progresses at different points) are specified.
Within the withAnimation
block, the opacity
state variable toggles between 0.0
and 1.0
depending on its current value. If the current opacity is 0.0
, it’s updated to 1.0
, and the view smoothly fades in over the duration of the animation. The opposite occurs if the current opacity is 1.0
.
The button’s label text also dynamically changes based on the opacity
state variable. If the opacity is 0.0
(indicating that the text is invisible), the button displays Fade In. Conversely, if the opacity is 1.0
(indicating that the text is fully visible), the button displays Fade Out.
Therefore, the button triggers a fade-in-fade-out animation on the Text
view, which toggles its visibility each time it is pressed.
In summary, animating a view’s opacity in SwiftUI involves creating a state variable to track the current opacity value, applying the opacity
modifier to integrate this variable into the view’s appearance and using an animation
modifier to specify the animation’s characteristics. Happy coding!