Chapters

Hide chapters

SwiftUI Cookbook

Live Edition · iOS 16.4 · Swift 5.8.1 · Xcode 14.3.1

Declare an Animation in SwiftUI
Written by Team Kodeco

Animations are an essential part of creating great user interfaces. In SwiftUI, you can easily add animations to your views with just a few lines of code. One of the fundamental elements of adding an animation in SwiftUI is declaring the animation itself.

To declare an animation in SwiftUI, you can use the animation modifier. This modifier takes an animation type and applies it to the view to which it’s attached. There are several types of animations that you can use in SwiftUI, including linear and spring animations.

Here’s an example of declaring a linear animation in SwiftUI:

struct ContentView: View {
  @State private var isAnimated = false
  
  var body: some View {
    RoundedRectangle(cornerRadius: 20)
      .fill(.blue)
      .frame(width: isAnimated ? 200 : 100, height: 100)
      .animation(.linear(duration: 1), value: isAnimated)
      .onTapGesture {
        isAnimated.toggle()
      }
  }
}

Your preview should look like this:

You can stretch a view in SwiftUI using a linear animation.
You can stretch a view in SwiftUI using a linear animation.

In this example, a linear animation of 1-second duration is declared using the animation modifier, with isAnimated state property as the observed value. The isAnimated property toggles between two different frame sizes using a ternary operator whenever the RoundedRectangle view is tapped. This change in state triggers the animation, which is applied to the frame size of the RoundedRectangle view, causing it to smoothly transition between the two sizes.

Aside from linear, SwiftUI provides several other animation types such as spring, easeInOut, easeIn and easeOut, each offering different visual effects. Feel free to explore these and find what suits your animation needs.

In conclusion, declaring an animation in SwiftUI is straightforward. With just a few lines of code, you can add fluid and engaging transitions to your apps, enhancing your app’s user experience.

Have a technical question? Want to report a bug? You can ask questions and report bugs to the book authors in our official book forum here.
© 2024 Kodeco Inc.