Chapters

Hide chapters

SwiftUI Cookbook

Live Edition · iOS 16.4 · Swift 5.8.1 · Xcode 14.3.1

Animate a View's Size in SwiftUI
Written by Team Kodeco

Animating a view’s size in SwiftUI is a great way to make your interface feel more dynamic and responsive. With just a few lines of code, you can make a button grow or shrink, an image expand or collapse or any other view element change size.

To animate a view’s size, you’ll use SwiftUI’s built-in animation modifier. Here’s an example:

struct ContentView: View {
  @State private var scale: CGFloat = 1.0

  var body: some View {
    Button("Tap Me!") {
      scale += 0.5
    }
    .scaleEffect(scale)
    .animation(.easeInOut(duration: 0.2), value: scale)
  }
}

Your preview should look like this:

Animate a scale effect to make UI elements grow or shrink.
Animate a scale effect to make UI elements grow or shrink.

In this example, you’ve created a new SwiftUI View that includes a button. A property scale is defined in the view, which is used to track the current scale factor of the button. Every time the button is tapped, you increment the scale property by 0.5.

To ensure a smooth transition of your button’s scale when it changes, you use the .animation(_:value:) modifier. This modifier is added to your button with a duration of 0.2 seconds and an ease-in, ease-out timing curve. The value parameter in the .animation modifier specifies that the animation should be applied whenever the value of the scale variable changes. This effectively means the button’s scale smoothly animates from its previous size to the new size every time it’s tapped.

Finally, you apply the scale property as a scaleEffect modifier to your button. This ensures that your button changes its scale according to the current value of the scale property. As scale changes due to the button being tapped, SwiftUI will automatically animate the scaleEffect to smoothly transition from the previous size to the new size, following the defined animation.

With just a few lines of code, you’ve created a dynamic, animated button that grows in size every time it’s tapped!

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.