首页 > 解决方案 > 导航时如何在 SwiftUI 中使用自定义视图转换?

问题描述

在基于 UIKit 的应用程序中,我们可以使用UIViewControllerAnimatedTransitioning协议进行自定义导航转换。

SwiftUI 中是否有等价物?

我知道我们已经可以在删除和添加视图之间进行动画处理。但是当我们 push 和 pop 到导航堆栈时我们怎么做呢?

标签: swiftui

解决方案


There isn't anything like this available in SwiftUI's APIs so far afaik. Make sure to open an enhancement request with Apple.

Implementing "navigation" on your own is a terrible idea, as you basically give all the accessibility and facility support afforded by UINavigationController.

Instead, here is a suggestion:

Either by means of a custom SwiftUI view or modifier, wrap the NavigationView with a UIViewControllerRepresentable wrapper, which in turn sets up a UIHostingController subclass, which waits for addChild(_:) to be called, which will be the navigation controller added as a child of the hosting controller. From here, if your animations are "static" (e.g. do not require any subview to subview transition), you can accomplish this here by implementing the navigation controller delegate, and providing the animation controller.

If you do need more evolved transitions (such as Photos.app's photo transition), you can create a custom UIViewRepresentable wrapper, which will serve as markers for "from" views and "to" views, you can then use those discover in UIKit, and e.g. can snapshot and animate in transitions.

Proposed API can look like this:

struct ContentView1: View {
    var body: some View {
        NavigationLink(destination: DetailView()) {
            Image("small").customSourceTarget()
        }.navigationBarTitle("Navigation")  
    }
}

struct ContentView2: View {
    var body: some View {
        Image("large").customTransitionTarget()
    }
}

NavigationView {
    ContentView1()
}.customAnimatable()

推荐阅读