.animation()
Published Jun 2, 2023Updated May 15, 2024
Contribute to Docs
The .animation()
modifier applies an animation to a view.
Syntax
View
.animation(animation, value: switchValue)
The .animation()
modifier takes two arguments:
- An animation type property or method, for example
.easeIn
or.easeIn(duration: 2)
. - A
value
that triggers the animation when theswitchValue
variable changes. This variable can be an integer or boolean.
Below is a table describing some of the animation type properties and methods.
Property or Method | Description |
---|---|
.easeIn |
Animation starts slow then speeds up. |
.easeIn(duration:) |
Same as .easeIn , but with a duration specified in seconds. |
.easeOut |
Animation starts fast then slows down. |
.easeOut(duration:) |
Same as .easeOut , but with a duration specified in seconds. |
.easeInOut |
Animation starts slow, speeds up, then slows down. |
.easeInOut(duration:) |
Same as .easeInOut , but with a duration specified in seconds. |
.linear |
Animation has a constant speed. |
.linear(duration:) |
Same as .linear , but with a duration specified in seconds. |
.spring() |
Animation behaves like a spring. response ,dampingFraction , and blendDuration can be optionally added as arguments to change the behaviour of the spring. |
Example
The following example shows text that fades in when a button is pressed:
import SwiftUIstruct AnimationView: View {@State private var showText = falsevar body: some View {VStack {Button("Show Secret Message") {showText.toggle()}.buttonStyle(.bordered)Text("Hello!").font(.largeTitle).opacity(showText ? 1 : 0).animation(.easeIn(duration: 2), value: showText)}}}
In the example above, showText
is initially set to false
, setting the opacity of the view Text("Hello!")
to be 0
, hiding the text.
When the button is pressed, showText
changes to be true
and triggers the animation, easing in the text to a visible opacity of 1
over a 2
second duration.
This will display:
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn SwiftUI on Codecademy
- Skill path
Build iOS Apps with SwiftUI
Learn how to build iOS applications with Swift and SwiftUI and publish them to Apples' App Store.Includes 7 CoursesWith CertificateBeginner Friendly13 hours - Free course
Learn Swift
A powerful programming language developed by Apple for iOS, macOS, and more.Beginner Friendly12 hours