如何在UIViewController
和struct ContentView
之间传递数据?
我尝试使用ObservableObject
,但无法获取最新数据。
答案 0 :(得分:5)
要将数据从UIViewController
传递到UIHostingController
内的SwiftUI结构,您可以将environmentObject
附加到SwiftUI rootView
:
let vc = UIHostingController(rootView: YourContentView().environmentObject(yourEnvironmentObject))
当然,您需要创建一个ObservableObject并将其添加到您的SwiftUI结构。
创建ObservableObject:
class TypeOfEnvironmentObject: ObservableObject {
@Published var data = "myData"
}
将其添加到您的结构中:
@EnvironmentObject var yourEnvironmentObject: TypeOfEnvironmentObject
答案 1 :(得分:1)
class myclassname: ObservableObject
在类中使用@Published var myvar
创建变量并创建init(myvar: type) {
self.myvar = myvar
}
UIViewController
中创建private var model = myclassname(myvar: XXX)
并在viewWillAppear------>let vc = myclassname(myvar: myvar)
let childView = UIHostingController(rootView: ContentView(model: vc))
中
struct ---> @ObservedObject var model: myclassname
答案 2 :(得分:0)
我发现现有答案令人困惑/不完整,也许是围绕Swift 5.3中的通用推断等进行了一些更改。虽然可以将环境对象添加到UIHostingController的视图中,但这似乎与类型冲突(即,UIHostingController的通用参数需要一个具体类型)。添加AnyView
可解决此问题:
import UIKit
import SwiftUI
struct TutorialView: View {
@EnvironmentObject private var integration: TutorialIntegrationService
var body: some View {
Text("Hi").navigationBarTitle("test: \(integration.id)")
}
}
class TutorialIntegrationService: ObservableObject {
@Published var id: Int = 0
}
class TutorialViewController: UIHostingController<AnyView> {
let integration = TutorialIntegrationService()
required init?(coder: NSCoder) {
super.init(coder: coder,rootView: AnyView(TutorialView().environmentObject(integration)));
}
}