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)
// 这里我们在形状上应用不对称过渡
.transition(.asymmetric(insertion: .slide, removal: .opacity))
}
}.padding(30)
Button("Click Me"){
withAnimation(.default){
anime.toggle()
}
}.font(.title).foregroundStyle(.brown)
}
}
#Preview {
ContentView()
}
输出
示例 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)
// 这里我们在形状上应用不对称过渡
.transition(.asymmetric(insertion: .slide, removal: .push(from: .top)))
}else{
RoundedRectangle(cornerRadius: 10)
.fill(.yellow)
.frame(width: 150, height: 100)
// 这里我们在形状上应用不对称过渡
.transition(.asymmetric(insertion: .push(from: .top), removal: .slide))
}
}.padding(30)
Button("Click Me"){
withAnimation(.default){
anime.toggle()
}
}.font(.title).foregroundStyle(.brown)
}
}
#Preview {
ContentView()
}
输出

