SwiftUI is a powerful framework for building user interfaces in iOS, macOS, watchOS, and tvOS. One of its most impressive features is the ability to create custom animations. In this blog post, we will explore how to build custom SwiftUI animations using the Animation
struct and other related tools.
In SwiftUI, animations are created by applying them to property changes. The Animation
struct provides a variety of options for customizing the timing and easing of animations.
- Creating Basic Animations
To create a basic animation, simply apply the Animation
struct to a property change. For example, to animate a view's opacity over 0.5 seconds:
- Customizing Animations
The Animation
struct provides a variety of options for customizing animations, including:
- Duration: The length of the animation in seconds.
- Delay: The delay before the animation starts.
- Ease: The easing function used for the animation.
- Repeat: The number of times the animation should repeat.
- Autoreverse: Whether the animation should reverse after completing.
For example, to create an animation that fades in over 1 second, then fades out over 1 second, and repeats 3 times:
struct MyView: View {
@State private var isVisible = false
var body: some View {
VStack {
Text("Hello, world!")
.opacity(isVisible ? 1.0 : 0.0)
.animation(.easeInOut(duration: 1).repeat(3).autoreverse())
}
}
}
- Combining Animations
You can combine multiple animations using the +
operator. For example, to create an animation that both fades in and scales up:
- Advanced Animations
For more advanced animations, you can use the withAnimation
modifier to apply animations to multiple property changes at once. You can also create custom easing functions using the Animation
struct's timingCurve
method.