我正在尝试从SwiftUI结构(名字和姓氏)传递数据,并且似乎无法用UIViewControllerRepresentable中的数据更新UIViewController中的变量。
我已经检查并确认我要从SwiftUI视图传递的数据是正确的。我需要做什么/更改以更新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)
}
)
}
}
}
答案 0 :(得分:1)
创建可表示的视图控制器,您可以将参数设置为一个控制器,但返回另一个。可能您的意思是:
//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
}