NEW: Get your ticket for Hacking with Swift Live 2019! >>

< How to adjust views by tinting, and desaturating, and more   How to create a spring animation >

How to create a basic animation

SwiftUI has built-in support for animations with its animation() modifier. To use this modifier, place it after any other modifiers for your views, and tell it what kind of animation you want.

For example, this code creates a button that increases its scale effect by 1 each time it’s pressed:

struct ContentView: View {
    @State var scale: Length = 1

    var body: some View {
        Button(action: {
            self.scale += 1
        }) {
            Text("Tap here")
                .scaleEffect(scale)
                .animation(.basic())
        }
    }
}

You can specify a precise duration for the animation if you want. For example, this animates the scale effect over three seconds:

Text("Tap here")
    .scaleEffect(scale)
    .animation(.basic(duration: 3))

You can also specify a curve, choosing between .easeIn, .easeOut, .easeInOut, and .custom, where the latter lets you specify your own control points.

For example, this animates the scale effect so that it starts slow and gets faster:

Text("Tap here")
    .scaleEffect(scale)
    .animation(.basic(curve: .easeIn))

You can animate many other modifiers, such as 2D and 3D rotation, opacity, border, and more. For example, this makes a button that spins around and increases its border every time it’s tapped:

struct ContentView: View {
    @State var angle: Double = 0
    @State var borderThickness: Length = 1

    var body: some View {
        Button(action: {
            self.angle += 45
            self.borderThickness += 1
        }) {
            Text("Tap here")
                .padding()
                .border(Color.red, width: borderThickness)
                .rotationEffect(.degrees(angle))
                .animation(.basic())
        }
    }
}

HACKING WITH SWIFT LIVE This July is a new two-day event where you'll be inspired by great speakers on day one then learn all the amazing new features from WWDC on day two – click here for more information and tickets.

< How to adjust views by tinting, and desaturating, and more   How to create a spring animation >
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.5/5

Click here to visit the Hacking with Swift store >>