将数据从 UIViewControllerRepresentable 传递到 UIViewController

Passing data from UIViewControllerRepresentable to UIViewController

我正在尝试从 SwiftUI 结构(名字和姓氏)传递数据,但似乎无法使用 UIViewControllerRepresentable 中的数据更新 UIViewController 中的变量。

我已经检查并确认我尝试从 SwiftUI 视图传入的数据是正确的。 do/change 我需要做什么来更新我的 UIViewController 中的 firstName 和 lastName 变量?

import UIKit
import PDFKit
import SwiftUI

class PDFPreviewViewController: UIViewController {
    public var documentData: Data?

    var firstName: String = "firstName did not load"
    var lastName: String = "lastName did not load"

    @IBOutlet weak var pdfView: PDFView!

    override func viewDidLoad() {
        super.viewDidLoad()

        let pdfCreator = PDFCreator(firstName: firstName, lastName: lastName, format: "test format")
        documentData = pdfCreator.createReleasePDF()
        if let data = documentData {
            pdfView.document = PDFDocument(data: data)
            pdfView.autoScales = true
        }
    }
}

struct PDFPreviewController: UIViewControllerRepresentable {
    var release: ModelRelease
    let vc = PDFPreviewViewController()

    func makeUIViewController(context: UIViewControllerRepresentableContext<PDFPreviewController>) -> UIViewController {

        let storyboard = UIStoryboard(name: "Preview", bundle: Bundle.main)
        let controller = storyboard.instantiateViewController(identifier: "Preview")

        vc.firstName = release.firstName
        vc.lastName = release.lastName

        return controller
    }

    func updateUIViewController(_ uiViewController: UIViewController, context: UIViewControllerRepresentableContext<PDFPreviewController>) {
    }
}

struct PDFPreviewControllerWrapper: View {
    @Environment(\.presentationMode) var presentationMode

    var release: ModelRelease

    var body: some View {
        NavigationView {
            PDFPreviewController(release: release)
            .navigationBarTitle(Text("Preview"))
            .navigationBarItems(trailing: Button(action: {
                self.presentationMode.wrappedValue.dismiss()
            }) {
                Text("Done")
                    .fontWeight(.bold)
                }
            )
        }
    }
}

创建可表示的视图控制器,您将参数设置到一个控制器,但 return 另一个。可能你的意思是:

//let vc = PDFPreviewViewController() // don't think it is needed at all

func makeUIViewController(context: UIViewControllerRepresentableContext<PDFPreviewController>) -> UIViewController {

    let storyboard = UIStoryboard(name: "Preview", bundle: Bundle.main)
    let controller = storyboard.instantiateViewController(identifier: 
                         "Preview") as! PDFPreviewViewController

    controller.firstName = release.firstName // << here !
    controller.lastName = release.lastName   // << and here !

    return controller
}