SwiftUI - Create Explicit Animation



Explicit animations allow us to define how, when, and what type of animation should be used on the given view explicitly. It provides manual control to the developers so that they can have more control over the animation. Using explicit animation we can easily mix two or more animations together to create a new effect on the simple as well as complex view. In SwiftUI, we can create explict animation using .withAnimation() modifier.

The ".withAnimation()" Modifier

The ".withAnimation()" modifier is used to animate all the components present in the given view when the state changes. Or we can say that it will automatically animate the transitions of the given view depending upon the state-changing code defined in the withAnimation() block. It allows us to manually control the animation according to our needs.

Syntax

Following is the syntax −

func withAnimation<Result>(
   _animation: Animation? = .default,
   _body: () throws -> Result
)rethrows -> Result

Example 1

The following SwiftUI program is used to create explicit animation. Here we change the opacity of the rectangle by clicking on the button.

import SwiftUI

struct ContentView: View {
   @State private var myOpacity = false
   var body: some View {
      Rectangle()
         .frame(width: 150, height: 100)
         .opacity(myOpacity ? 0.2 : 2)
      Button("Change Opacity"){
         withAnimation(.easeInOut(duration: 1.3)){
            myOpacity.toggle()
         }
      }.font(.largeTitle).foregroundStyle(.brown)
   }
}
#Preview {
   ContentView()
}

Output

Create Explicit Animation

Example 2

The following SwiftUI program is used to run a truck linearly.

import SwiftUI

struct ContentView: View {
   @State private var run = false
   var body: some View {
      Image(systemName: "box.truck")
         .font(.largeTitle)
         .foregroundColor(.green)
         .offset(x: run ? 1400 : -140, y: 0)
      Button("Run The Truck"){
         withAnimation(.linear(duration: 0.9)){
            run.toggle()
         }
      }.font(.title2).foregroundStyle(.brown)
   }
}
#Preview {
   ContentView()
}

Output

Create Explicit Animation

Implicit Vs Explicit Animation

As we know in SwiftUI, we can create animation in two different types: implicit and explicit animations. Both animations animates the views but still, they have some differences and the differences are as follows −

Implicit Animation Explicit Animation
It triggers automatically when the stage changes. It trigger manually inside the withAnimation() block.
It applies directly to the view with the help of the .animation() modifier. It applies to state changes present inside the withAnimation block.
It provides minimal control over the animation. It provides full control over the animation.
It is good for simple animations. It is best for simple as well as complex animations.
It is less flexible but easy to use. It is more flexible.
Advertisements