使用UIHostingController访问其addSubview中的ViewController数据

时间:2020-08-27 02:48:18

标签: swift swiftui

我有一个嵌入在视图控制器中的表单,如下所示:

    let formController = UIHostingController(rootView: PostCallForm())
    if let form = formController.view {
        form.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(form)
        self.addChild(formController)

嵌入该视图的视图通过MVC设置获取数据,如下所示:

class ClientInfoController: UIViewController {

var client: Calls? {
    didSet {
        infoLabel.text = client?.callID
    }
}

我的表单位于单独的文件form.swift中:

struct PostCallForm: View {
  
    var body: some View {
        NavigationView {
            Form {
                Toggle(isOn: $submission.fieldOne ) {
                    Text("Field One")
                }
                Toggle(isOn: $submission.fieldTwo ) {
                    Text("Field Two")
                }
                Toggle(isOn: $submission.fieldThree ) {
                    Text("Field Three")
                }
                
                Section {
                    Button(action: {
                        self.placeSubmission()
                    }){
                        Text("Submit")
                    }
                }

            }
                
        .alert(isPresented: $showingConfirmation) {
            Alert(title: Text("Call Submitted!"), message: Text(confirmationMessage), dismissButton: .default(Text("Dismiss")) 
    
                )
            }
        }
    }

我需要能够访问表单中的ViewController var client: Calls?数据,以便可以在表单的完成处理程序中引用client.callID。最好的非骇客方式是什么?

1 个答案:

答案 0 :(得分:1)

这是可行的方法:

// Introduce view model for form
class FormViewModel: ObservableObject {
    @Published var client: Calls? = nil
}

class ClientInfoController: UIViewController {
private var formVM = FormViewModel() // create form view model 

var client: Calls? {
    didSet {
        infoLabel.text = client?.callID
        formVM.client = client            // << update !!
    }
}

...
    let formController = UIHostingController(rootView: 
         PostCallForm().environmentObject(formVM))       // << inject !!

...

struct PostCallForm: View {
    @EnvironmentObject var vm: FormViewModel      // << use !!
  
    var body: some View {