SwiftUI - 非對稱過渡



非對稱過渡是一種特殊的過渡型別,使用它我們可以為檢視的出現和消失指定不同的過渡方式。例如,檢視的出現使用滑動過渡,而檢視的消失使用不透明度過渡。此方法用於 `.transition()` 修飾符內。

語法

以下是語法:

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

引數

此方法採用以下引數:

  • insertion: 表示檢視的插入過渡。

  • removal: 表示檢視的移除過渡。

示例 1

在下面的 SwiftUI 程式中,我們將非對稱過渡應用於圓角矩形。此處圓角矩形使用滑動過渡進入,並使用不透明度過渡退出螢幕。

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()
}

輸出

Asymmetric Transition

示例 2

在下面的 SwiftUI 程式中,我們為兩種(真和假)狀態更改應用不同的非對稱過渡。

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()
}

輸出

Asymmetric Transition
廣告
© . All rights reserved.