SwiftUI - Asymmetric Transition



Asymmetric transition is a special type of transitions, using this we can specify different transitions for the appearance and disappearance of the view. For example, the appearance of the view uses a slide transition and the disappearance of the view uses an opacity transition. This method is used inside the .transition() modifier.

Syntax

Following is the syntax −

static func asymmetric(insertion: AnyTransition, 
   removal: AnyTransition) -> AnyTransition

Parameters

This method takes the following parameters −

  • insertion: Represent the insertion transition for the view.

  • removal: Represent the removal transition for the view.

Example 1

In the following SwiftUI program, we apply an asymmetric transition to the rounded rectangle. Here the rounded rectange enters using slide transition and exits from the screen using opacity transition.

import SwiftUI
struct ContentView: View {    
   @State private var anime = false   
   var body: some View {   
      ZStack{
         if anime{
            RoundedRectangle(cornerRadius: 10)
               .fill(.red)
               .frame(width: 150, height: 100)            
               // Here we apply asymmetric transition on the shape
               .transition(.asymmetric(insertion: .slide, removal: .opacity))
         }
      }.padding(30)      
      Button("Click Me"){
         withAnimation(.default){
            anime.toggle()
         }
      }.font(.title).foregroundStyle(.brown)
   }
}
#Preview {
   ContentView()
}

Output

Asymmetric Transition

Example 2

In the following SwiftUI program, we apply different asymmetric transitions for both(true and false) state changes.

import SwiftUI
struct ContentView: View {   
   @State private var anime = false   
   var body: some View {   
      ZStack{
         if anime{
            RoundedRectangle(cornerRadius: 10)
            .fill(.red)
            .frame(width: 150, height: 100)            
            // Here we apply asymmetric transition on the shape
            .transition(.asymmetric(insertion: .slide, removal: .push(from: .top)))
         }else{
            
            RoundedRectangle(cornerRadius: 10)
            .fill(.yellow)
            .frame(width: 150, height: 100)
            
            // Here we apply asymmetric transition on the shape
            .transition(.asymmetric(insertion: .push(from: .top), removal: .slide))
            
         }
      }.padding(30)      
      Button("Click Me"){
         withAnimation(.default){
            anime.toggle()
         }
      }.font(.title).foregroundStyle(.brown)
   }
}
#Preview {
   ContentView()
}

Output

Asymmetric Transition
Advertisements