Sebastien Desemberg
Sebastien Desemberg

Reputation: 321

Pass a variable from UIHostingController to SWIFTUI view

I have a storyboard app and now starting with SwiftUI views in my existing app. I have a API calls that populates variables eg: name, surname, email and mobile.

How do I pass the UIKit variable in my UIHostingController to display in SwiftUI view?

My storyboard UIKit file:

import UIKit
import SwiftUI
class UserDashboardHostVC: UIViewController {
    
    var name = String()
    var surname = String()
    var email = String()
    var mobile = String()
    

    override func viewDidLoad() {
        super.viewDidLoad()
        
        getAPIdata() 
        //this populates the above 4 variables.    
        
        let controller = UIHostingController(rootView: UserDashboard())
        controller.view.translatesAutoresizingMaskIntoConstraints = false
        self.addChild(controller)
        self.view.addSubview(controller.view)
        controller.didMove(toParent: self)
    }
}

My SwiftUI view:

import SwiftUI

struct UserDashboard: View {
    
    var body: some View {
        NavigationView{

           Text(name)
           Spacer()
           Text(surname)
           Spacer()
           Text(email)
           Spacer()
           Text(mobile)
           Spacer()
       }
    }
}

Upvotes: 3

Views: 4626

Answers (1)

Asperi
Asperi

Reputation: 258365

Move those properties from controller into standalone view model class and pass instance of that class into SwiftUI view, like shown below.

*Also you can pass same model into getAPI function to update model's properties. (Note: properties must be updated on main queue to refresh SwiftUI view!)

class UserDashboardModel: ObservableObject {
    @Published var name = String()
    @Published var surname = String()
    @Published var email = String()
    @Published var mobile = String()
}

class UserDashboardHostVC: UIViewController {

    var model = UserDashboardModel()      // << here owner !!


    override func viewDidLoad() {
        super.viewDidLoad()

        getAPIdata()             // << can be injected here
        //this populates the above 4 variables.

        let controller = UIHostingController(rootView: UserDashboard(model: self.model))     // << here !!
        controller.view.translatesAutoresizingMaskIntoConstraints = false
        self.addChild(controller)
        self.view.addSubview(controller.view)
        controller.didMove(toParent: self)
    }
}

struct UserDashboard: View {
    @ObservedObject var model: UserDashboardModel    // << here !!

    var body: some View {
        NavigationView{

           Text(model.name)
           Spacer()
           Text(model.surname)
           Spacer()
           Text(model.email)
           Spacer()
           Text(model.mobile)
           Spacer()
       }
    }
}

Upvotes: 1

Related Questions