[英]Passing Data from SwiftUI View to UIViewController
I've been testing SwiftUI to see how far I can go with it.我一直在测试SwiftUI以了解 go 能走多远。 Now, I want to find out whether or not I can pass a string from SwiftUI
View
directly to UIViewController
.现在,我想知道是否可以将字符串从 SwiftUI
View
直接传递给UIViewController
。 And I want to display this string with UILabel
.我想用
UILabel
显示这个字符串。 UILabel
is all I have on my storyoboard. UILabel
是我故事板上的全部内容。
The following is my view controller ( UIViewController
).以下是我的看法 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>) {
}
}
My SwiftUI View
is the following.我的 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)
}
}
}
I hoped that I could just pass a string with HomeViewControllerRepresentation.我希望我可以通过 HomeViewControllerRepresentation 传递一个字符串。 But it won't work.
但它不会起作用。 Is there a simple way of passing data from SwiftUI
View
to UIViewController
?有没有一种简单的方法可以将数据从 SwiftUI
View
传递到UIViewController
? Thanks.谢谢。
UIViewControllerRepresentable
is not a proxy, but wrapper, so everything should be transferred manually, like 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.