支持遗留项目中的 SwiftUI 导航

Fer*_*ndo 9 ios ios13 swiftui navigationlink

我想知道是否有任何方法可以在遗留项目中开始使用SwiftUI并且仍然能够在SwiftUI场景中来回导航。也就是说,让我们想象一下,我只想为去年我一直在从事的项目支持最新的iOS 13。一切都建立在UIKit之上,导航以通常的方式呈现或推送视图控制器。

现在我想开始使用 SwiftUI,所以我在我的项目的 General 中启用了该选项,目标iOS 13,在Info.plist 中获取我的SceneDelegate和我的新键值对。为了导航到Swift UI场景,我可以推送一个UIHostingViewController,其 rootView 将是我新设计的SwiftUI视图。但是如何使用NavigationLink推送旧的UIKit视图控制器?

class ViewController: UIViewController {

    @IBAction func userDidTapGo(_ sender: Any) {
        let contentView = ContentView()
        navigationController?.pushViewController(UIHostingController(rootView: contentView), animated: true)
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        title = "UIKit"
    }
}

struct ContentView: View {
    var body: some View {
        NavigationView {
            NavigationLink(destination: /* what should be here?? */) {
                Text("Go to UIKit")
            }

        }.navigationBarTitle("Swift UI")
    }
}
Run Code Online (Sandbox Code Playgroud)

Yon*_*nat 1

您需要将旧的视图控制器包装在UIViewControllerRepresentable包装器中。Apple 有一个很好的教程:Interfaceing with UIKit

它效果很好,可以让您重用旧代码,而不是从头开始重写所有内容。