Skip to main content

How to create an explicit animation

About 2 minSwiftSwiftUIArticle(s)bloghackingwithswift.comcrashcourseswiftswiftuixcodeappstore

How to create an explicit animation 관련

SwiftUI by Example

Back to Home

How to create an explicit animation | SwiftUI by Example

How to create an explicit animation

Updated for Xcode 15

If you attach an animation modifier to a view, you end up with implicit animation – changing some state elsewhere in your view might use animation, even though you’re just incrementing an integer or toggling a Boolean.

An alternative is to use explicit animation, where you don’t attach modifiers to the view in question but instead ask SwiftUI to animate the precise change you want to make. To do this, wrap your changes in a call to withAnimation().

For example, this uses explicit animation to make a button fade away slightly more each time it’s tapped:

struct ContentView: View {
    @State private var opacity = 1.0

    var body: some View {
        Button("Press here") {
            withAnimation {
                opacity -= 0.2
            }
        }
        .padding()
        .opacity(opacity)
    }
}

Download this as an Xcode projectopen in new window

withAnimation() takes a parameter specifying the kind of animation you want, so you could create a three-second linear animation like this: withAnimation(.linear(duration: 3))

Explicit animations are often helpful because they cause every affected view to animate, not just those that have implicit animations attached. For example, if view A has to make room for view B as part of the animation, but only view B has an animation attached, then view A will jump to its new position without animating unless you use explicit animations.

Similar solutions…
How to create a spring animation | SwiftUI by Example

How to create a spring animation
How to start an animation immediately after a view appears | SwiftUI by Example

How to start an animation immediately after a view appears
How to delay an animation | SwiftUI by Example

How to delay an animation
How to run a completion callback when an animation finishes | SwiftUI by Example

How to run a completion callback when an animation finishes
SwiftUI tips and tricks | SwiftUI by Example

SwiftUI tips and tricks

이찬희 (MarkiiimarK)
Never Stop Learning.