'SwiftUI: Why does @State work, and not @StateObject
Why does @State and @ObservedObject causes the SwiftUIView to be redrawn and updated correctly, but not when using @StateObject?
Thanks
public class Model: ObservableObject {
@Published public var randomStrings: [String] = []
}
class DebugTestVC: UIViewController {
// ***** WORKS *****:
@State var model = Model()
// ***** WORKS *****:
@ObservedObject var model = Model()
// ***** NOT WORKING *****:
@StateObject var model = Model()
override func viewDidLoad() {
super.viewDidLoad()
model.randomStrings = ["1", "2"]
let vc = UIHostingController(rootView: SwiftUIView(model: model))
vc.view.frame = UIScreen.main.bounds
addChild(vc)
view.addSubview(vc.view)
vc.didMove(toParent: self)
}
}
struct SwiftUIView: View {
@ObservedObject var model: Model
var body: some View {
VStack {
ForEach(model.randomStrings, id: \.self) { string in
Text(string)
}
}
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|