如何在使用 SwiftUI 的同时导航到视图控制器?

Pet*_*nes 7 ios swift swiftui

我正在尝试导航到视图控制器,同时使用 SwiftUI 中的 NavigationLink。我假设我无法做到这一点,所以我想知道如何以另一种方式导航到我的视图控制器,同时仍然能够单击我的 HomeView 中的按钮并导航到我的 ViewController。

下面是我的 HomeView,我想要一个带有文本“Time Sheets”的按钮来导航到我的 ViewController

struct HomeView: View {
    var body: some View {
        NavigationView {
        VStack {
            Image("OELogo")
                .resizable()
                .frame(width: 400, height: 300)
            
            NavigationLink(destination: ViewController()) {
                Text("Time Sheets")
                .fontWeight(.bold)
                    .frame(minWidth: 325, minHeight: 50)
                .font(.title)
                .foregroundColor(.gray)
                .padding()
                .overlay(
                    RoundedRectangle(cornerRadius: 50)
                        .stroke(Color.gray, lineWidth: 2)
                )
            }
Run Code Online (Sandbox Code Playgroud)

下面是我想要导航到的 ViewController 文件代码的开始

import UIKit
import KVKCalendar
import SwiftUI

final class ViewController: UIViewController {
    private var events = [Event]()
    
    private var selectDate: Date = {
        let formatter = DateFormatter()
        formatter.dateFormat = "dd.MM.yyyy"
        return formatter.date(from: "27.7.2020") ?? Date()
    }()```

Run Code Online (Sandbox Code Playgroud)

Chr*_*ido 8

为了实现这一点,您需要创建一个struct符合UIViewControllerRepresentable. 这就像UIKits的包装器UIViewController。有一个类似的协议UIViewUIViewRepresentable

struct YourViewControllerView: UIViewControllerRepresentable {
    func makeUIViewController(context: Context) -> ViewController {
        // this will work if you are not using Storyboards at all.
        return ViewController()
    }

    func updateUIViewController(_ uiViewController: ViewController, context: Context) {
        // update code   
    }

}
Run Code Online (Sandbox Code Playgroud)

或者,struct如果您有ViewController故事板,那么这将起作用。

struct YourViewControllerViewWithStoryboard: UIViewControllerRepresentable {
    func makeUIViewController(context: Context) -> ViewController {
        guard let viewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(identifier: "ViewController") as? ViewController else {
            fatalError("ViewController not implemented in storyboard")
        }
        return viewController
    }

    func updateUIViewController(_ uiViewController: ViewController, context: Context) {
        // update code
    }
}
Run Code Online (Sandbox Code Playgroud)

如果您使用故事板,请记住在界面构建器中设置Restoration IDStoryboard ID