[英]Passing Data from SwiftUI View to UIViewController
我一直在測試SwiftUI以了解 go 能走多遠。 現在,我想知道是否可以將字符串從 SwiftUI View
直接傳遞給UIViewController
。 我想用UILabel
顯示這個字符串。 UILabel
是我故事板上的全部內容。
以下是我的看法 controller ( UIViewController
)。
import UIKit
import SwiftUI
class HomeViewController: UIViewController {
var message = String()
@IBOutlet weak var messageLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
messageLabel.text = message
}
}
struct HomeViewControllerRepresentation: UIViewControllerRepresentable {
func makeUIViewController(context: UIViewControllerRepresentableContext<HomeViewControllerRepresentation>) -> HomeViewController {
UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "homeViewController") as! HomeViewController
}
func updateUIViewController(_ uiViewController: HomeViewController, context: UIViewControllerRepresentableContext<HomeViewControllerRepresentation>) {
}
}
我的 SwiftUI View
如下。
import SwiftUI
struct ContentView: View {
var body: some View {
NavigationView {
VStack {
NavigationLink(destination: HomeViewControllerRepresentation(message: "GGG")) { // Error
Text("Tap me")
}
}
.navigationBarTitle("")
.navigationBarHidden(true)
}
}
}
我希望我可以通過 HomeViewControllerRepresentation 傳遞一個字符串。 但它不會起作用。 有沒有一種簡單的方法可以將數據從 SwiftUI View
傳遞到UIViewController
? 謝謝。
UIViewControllerRepresentable
不是代理,而是包裝器,所以一切都應該手動傳輸,比如
struct HomeViewControllerRepresentation: UIViewControllerRepresentable {
var message: String
func makeUIViewController(context: UIViewControllerRepresentableContext<HomeViewControllerRepresentation>) -> HomeViewController {
let controller = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "homeViewController") as! HomeViewController
controller.message = self.message
return controller
}
func updateUIViewController(_ uiViewController: HomeViewController, context: UIViewControllerRepresentableContext<HomeViewControllerRepresentation>) {
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.