Vishwanath Deshmukh
Vishwanath Deshmukh

Reputation: 649

How to access/modify parent view variable in subviews?

I have parent view container which holds multiple subviews.

struct Person {
  var name: String
  var lastname: String
}

class ParentContainer: UIView {
 var person = Person(name: "Vish", lastname: "Deshmukh")
 let child1 = ChildView1(person)
 let child2 = ChildView2(person)
 let child3 = ChildView3(person)
}

How should I make sure if any of the child change person object, reflect that value everywhere including other child views and parent Container view?

Upvotes: 0

Views: 277

Answers (1)

Duncan C
Duncan C

Reputation: 131398

This actually a fairly involved topic. If Person was a reference object, you could have your child views watch for changes to the Person. However, that's not really following best practices.

Modern design is moving to UDF (unidirectional data flow) where you have a value object that describes the current state of your UI and it gets passed around when it changes. With UDF, the child wouldn't change the person object - instead they would create a new, immutable person object containing changes, and notify subscribers that there is an updated person object. The children would be observing changes to the Person object.

The specifics depend on how you're implementing your app.

Upvotes: 1

Related Questions