I have the business logic in Swift class and built UI using SwiftUI. Below the high level code that shows how SwiftUI and its subview receives the data from Swift. Please let me know if its correct approach
class SwiftClass{
var score = "1"
func A () {}
func B () {
// score will get updated frequently
let scoreModal = ScoreUIViewModel()
let scoreUI: ScoreUI = ScoreUI(showModal: .constant(true), scoreUIViewModel: scoreModal)
DispatchQueue.main.async {
scoreUI.displayScoreUI()
}
// score getting updated from another class
scoreModal.score = score
// score getting updated from another class
score = "2"
scoreModal.score = "2"
// score getting updated from another class
score = "3"
scoreModal.score = "3"
// score getting updated from another class
score = "4"
scoreModal.score = "4"
.......
}
}
import SwiftUI
class ScoreUIViewModel: Observable {
@Published score: String
}
struct ScoreUI: View {
@State var scoreUIViewModel: ScoreUIViewModel
func displayScoreUI() {
let hostController = UIHostingController(rootView: ScoreUI())
hostController = .overCurrentContext
topViewController()!.present(hostController, animated: true, completion: nil)
}.environmentObject(scoreUIViewModel)
}
struct ScoreText: View {
@EnvironmentObject var scoreUIViewModel: ScoreUIViewModel
Text(score).foregroundColor(.green)
}