SwiftUI-转场

宋明    |     2023/03/18 posted in    SwiftUI

  • transition 转场动画
  • combined 组合方法

对称转场动画

//
//  ContentView.swift
//  swiftUI_01
//
//  Created by 宋明 on 2023/3/1.
//

import SwiftUI




struct ContentView: View {
    @State private var show = true
    
    var body: some View {
        
        VStack {
            
            RoundedRectangle(cornerRadius: 10)
                .frame(width: 300, height: 300)
                .foregroundColor(.green)
                .overlay(
                    Text("Show details")
                        .font(.system(.largeTitle, design: .rounded))
                        .bold()
                        .foregroundColor(.white)
                    
                )
            
            
            
            if show {
                RoundedRectangle(cornerRadius: 10)
                    .frame(width: 300, height: 300)
                    .foregroundColor(.purple)
                    .overlay(
                        Text("Well, here is the details")
                            .font(.system(.largeTitle, design: .rounded))
                            .bold()
                            .foregroundColor(.white)
                    )
                //加入转场动画
                .transition(AnyTransition
                            //位移
                    .offset(x: -600, y: 0)
                            //缩放
                    .combined(with: .scale)
                            //透明度
                    .combined(with: .opacity))
            }
        }
        
        .onTapGesture {
            withAnimation(.spring()) {
                self.show.toggle()
            }
            
        }
    }
}


struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

2023-03-06_15-26-04 (1).gif

注 如果动画需要反复使用 可以扩展AnyTransition

extension AnyTransition {
    static var offsetScaleOpacity: AnyTransition {
        AnyTransition.offset(x: -600, y: 0).combined(with: .scale).combined(with: .opacity)
    }
}

//加入转场动画
                // .transition(AnyTransition
                            //位移
                    // .offset(x: -600, y: 0)
                            //缩放
                    // .combined(with: .scale)
                            //透明度
                    // .combined(with: .opacity))

.transition(.offsetScaleOpacity)

不对称转场动画

使用.assymetric 方法 分别设置入场出场动画

注:Xcode Version 14.2 (14C18) 14promax 虚拟 不生效

AnyTransition.asymmetric(
            insertion: .scale(scale: 0, anchor: .bottom),
            removal: .opacity
        )