如何反转 SwiftUI 动画的幻灯片过渡?

How can I reverse the slide transition for a SwiftUI animation?

我正在处理一系列屏幕,这些屏幕应该在按下按钮时发生变化,并且应该 in/out 从右向左滑动。
除了 .slide 过渡使它从前缘移入并移出到后缘外,一切都运行良好。 (从左到右)
我想在不改变 trailing/leading 的情况下反转过渡动画方向(至少不是在应用程序的整个上下文中)。

我尝试将过渡更改为 .move(edge: .trailing),但随后视图从同一方向进出。

import SwiftUI

struct ContentView: View {
    enum screens {
        case start, mid, final
    }
    @State var curScreen: screens = .start
    
    func changeScreen() {
        switch curScreen {
        case .start:
            curScreen = .mid
        case .mid:
            curScreen = .final
        case .final:
            return
        }
    }
    
    var body: some View {
        switch curScreen {
        case .start:
            ScreenView(callback: changeScreen, text: "Start")
                .transition(.slide)
        case .mid:
            ScreenView(callback: changeScreen, text: "Mid")
                .transition(.slide)
        case .final:
            ScreenView(callback: {}, text: "Final")
                .transition(.slide)
        }
    }
}

struct ScreenView: View {
    let callback: () -> ()
    let text: String
    var body: some View {
        Text(text)
            .padding()
            .frame(maxWidth: .infinity)
            .onTapGesture {
                withAnimation(.default) {
                    callback()
                }
            }
    }
}

已经回答了我的问题,但是在google或者Whosebug上搜索的时候都没有出现,所以这里再说一遍算法:

如何在 SwiftUI 中反转幻灯片过渡:

摘自 Apple 开发者文档:

static var slide: AnyTransition
// A transition that inserts by moving in from the leading edge, and removes by moving out towards the trailing edge.

也可以写成:

AnyTransition.asymmetric(
    insertion: .move(edge: .leading),
    removal: .move(edge: .trailing)
)

所以要反转动画只需翻转 insertionremoval 并将其放入您的过渡 ViewModifier。

因为我需要多次使用它,所以我对 AnyTransition 进行了扩展,这样我就可以调用 .transition(.backslide)

extension AnyTransition {
    static var backslide: AnyTransition {
        AnyTransition.asymmetric(
            insertion: .move(edge: .trailing),
            removal: .move(edge: .leading))}
}