Reputation: 2475
How do I write to observe the property passed from parent View?
struct ParentView: View {
@State var prop = "a"
var body: some View {
ChildView(prop: prop)
}
}
struct ChildView: View {
var prop: String { // When the "prop" changed, do something.
didSet {
print(prop) // not work
}
}
var body: some View {
Text(prop)
}
}
Upvotes: 0
Views: 289
Reputation: 2615
The ParentView
creates a new instance of ChildView
with a new value of prop
every time when @State var prop = "a"
change.
You can create a custom init and check a new value:
struct ChildView: View {
var prop: String
init(prop: String) {
self.prop = prop
print(prop) // <-- here
}
var body: some View {
Text(prop)
}
}
Upvotes: 1