将数据从UIKit传递到SwiftUI(容器UIHostingController)

时间:2020-05-11 15:04:53

标签: swift swiftui

如何在UIViewControllerstruct ContentView之间传递数据?

我尝试使用ObservableObject,但无法获取最新数据。

3 个答案:

答案 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)

  1. class myclassname: ObservableObject

  2. 在类中使用@Published var myvar创建变量并创建init(myvar: type) { self.myvar = myvar }

  3. 在我的UIViewController中创建private var model = myclassname(myvar: XXX)并在viewWillAppear------>let vc = myclassname(myvar: myvar) let childView = UIHostingController(rootView: ContentView(model: vc))
    1. 在我的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)));
    }
}