Triggering animations
So, how do we trigger animations? There are several ways to do so in SwiftUI, including using the following SwiftUI modifiers, methods, and functions:
- The
.animation()
modifier: This modifier allows you to specify the type of animation used when a view appears or disappears or when its state changes. - The
withAnimation()
function: This function allows you to wrap a block of code that changes the state of a view, and it will automatically animate the changes. - A gesture: This is a way to interact with a view by performing actions such as tapping, dragging, or pinching. You can use a gesture to trigger an animation when a certain action is performed on a view.
- A timer: This allows you to specify an animation to be performed over a certain period of time. You can use a timer to animate the changes to a view’s state over a specific duration.
- The
onAppear()
andonDisappear()
modifiers: These modifiers allow you to specify code to be executed when a view appears or disappears. These modifiers can trigger an animation when a view appears or disappears. - Button and other control views: A button, slider, picker, or other control type view in SwiftUI can be a trigger for an animation.
There are other ways to trigger animations, but these are the main ones that we will cover here. Whatever you choose will depend on the specific needs of your app and the behavior you want to produce. We will explore these different triggers when we start building our projects in the coming chapters.
Let’s continue by looking at various properties that can be animated in SwiftUI.