Say I have UserSettings
EnviornmentObject
and one of it's properties is a class, the problem is when I change a value of that class, the EnviornmentObject
won't publish these changes. I understand why, but I can't seem to find a workaround.
Here is a simplified code to show the problem:
struct TestView: View {
@EnvironmentObject var settings: UserSettings
var body: some View {
ZStack {
Text("test: \(self.settings.ob.val)")
VStack {
// This is the only one that works and that makes sense, it changes the entire object
Button(action: {
self.settings.changeOb(to: testOb(val: "1"))
}) {
Text("Change object")
}
// From here on nothing works, I tried different ways to change the object value
Button(action: {
self.settings.ob.changeVal(to: "2")
}) {
Text("Change object's val")
}
Button(action: {
self.settings.changeVal(to: "3")
}) {
Text("Change object's val V2")
}
Spacer()
}
}
}
}
struct TestView_Previews: PreviewProvider {
static var previews: some View {
return ZStack {
TestView().environmentObject(UserSettings(ob: testOb("abc")))
}
}
}
class testOb: ObservableObject {
@Published private(set) var val: String
init(val: String) {
self.val = val
}
func changeVal(to: String) {
self.val = to
}
}
class UserSettings: ObservableObject {
@Published private(set) var ob: testOb
init(ob: testOb) {
self.ob = ob
}
func changeOb(ob: testOb) {
self.ob = ob
}
func changeVal(to: String) {
self.ob.val(to: to)
}
}