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

vkc1a9a2  于 2023-06-25  发布在  iOS
关注(0)|答案(2)|浏览(123)

我正在处理一系列屏幕,这些屏幕应该在按下按钮时发生变化,并且应该从右向左滑入/滑出。
除了.slide过渡使它从前缘移进并移出到后缘外,一切都工作得很好。(从左至右)
我想反转过渡动画的方向,而不改变拖尾/前导是什么(至少不是在应用的整个上下文中)。
我尝试将过渡更改为.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()
                }
            }
    }
}
ryoqjall

ryoqjall1#

  • @Asperi已经回答了我的问题,但当我搜索它时,它没有出现在Google或StackOverflow上,所以这里再次为算法:*

如何在SwiftUI中反转幻灯片切换:

摘自Apple Developer Documentation:

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

e5nqia272#

iOS 16

Group {
                switch viewModel.selectedTab {
                    case .travel:
                        TravelSearchForm(viewModel: viewModel)
                    case .cars:
                        CarsSearchForm(viewModel: viewModel.carsForm)
                    case .rooms:
                        RoomsSearchForm(viewModel: viewModel.roomsForm)
                }
            }
            .transition(.dinamicSlide(forward: $viewModel.tabTransitionDirectionIsForward))
            .animation(.default, value: viewModel.selectedTab)

相关问题