NEW: Learn SwiftUI with my free YouTube video series! >>

< How to animate changes in binding values   How to add and remove views with a transition >

How to create an explicit animation

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(action: {
            withAnimation {
                self.opacity -= 0.2
            }
        }) {
            Text("Tap here")
                .padding()
                .opacity(opacity)
        }
    }
}

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)) {
    self.opacity -= 0.2
}

Explicit animations are often helpful because they cause every affected view to animation, 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.

LEARN SWIFTUI FOR FREE I wrote a massive, free SwiftUI tutorial collection, and also have a growing list of free SwiftUI tutorials on YouTube – get started today!

< How to animate changes in binding values   How to add and remove views with a transition >
MASTER SWIFT NOW
Buy Testing Swift Buy Practical iOS 12 Buy Pro Swift Buy Swift Design Patterns Buy Swift Coding Challenges Buy Server-Side Swift (Vapor Edition) Buy Server-Side Swift (Kitura Edition) Buy Hacking with macOS Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with Swift Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let me know!

Average rating: 4.8/5

Click here to visit the Hacking with Swift store >>