Created
June 25, 2020 19:14
-
-
Save cmsj/2e1998288f31477f414839819c39a88b to your computer and use it in GitHub Desktop.
Trying to use @observableobject and @EnvironmentObject, but changes in subviews don't propagate
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Person: RawRepresentable, ObservableObject { | |
@Published var name: String | |
@Published var age: Int | |
// RawRepresentable | |
var rawValue: String { | |
get { | |
let value = "\(name):\(age)" | |
print("Returning raw value: "+value) | |
return value | |
} | |
} | |
required init?(rawValue: String) { | |
if rawValue == "" { | |
print("Initialised with empty rawValue, setting defaults") | |
self.name = "Jonny Appleseed" | |
self.age = 42 | |
return | |
} | |
print("Initialising with rawValue: \(rawValue)") | |
let parts = rawValue.split(separator: ":") | |
self.name = String(parts[0]) | |
self.age = Int(parts[1])! | |
} | |
} | |
struct ContentView: View { | |
@AppStorage("person") var person: Person = Person(rawValue: "")! | |
var body: some View { | |
ContentSubview().environmentObject(person) | |
} | |
} | |
struct ContentSubview: View { | |
@EnvironmentObject var person: Person | |
var body: some View { | |
VStack { | |
TextField("Name: ", text: $person.name).padding() | |
TextField("Age: ", value: $person.age, formatter: NumberFormatter()).padding() | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment