How To Animate View In SwiftUI

We’re used to everything moves smoothly on your screens, it’s because of animation. To animate a view in SwiftUI you need only one line of code.

Let’s say you have one Text that will be animated and a Button that invokes animation. Both of them are inside VStack. The button doesn’t do anything yet.

VStack {
    
Text(“Hello, world!”)
    
    .padding(.bottom, 30)
    
Button(“Rotate”) {
    }
}

First, create State property that keeps how much view is rotated.

@State private var degrees = 0.0

Next, add .rotationEffect view modifier to Text. You can read more about views rotation here.

Text(“Hello, world!”)
    .
rotationEffect(.degrees(degrees))

And, increase degrees by 90 on each button click.

Button(“Rotate”) {
    
self.degrees += 90
}

When you run code, on each button click, the view will jump by 90 degrees.

The first option to make animation is to embed degrees changes with withAnimation.

Button(“Rotate”) {
    
withAnimation {
    
    self.degrees += 90
    }
}

Now, the text will move smoothly.

Another option is to add .animation view modifier to Text.

Text(“Hello, world!”)
    .
rotationEffect(.degrees(degrees))
    .
animation(.linear)
    .
padding(.bottom, 30)

In both cases, the result is the same.