Curnelious
Curnelious

Reputation: 1

Getting data from a container view

In my UIViewController A i have some container view, that loads some other UIViewController B. I want that UIViewController A will be able to know what happens in its own container.

Problem is, that I can't get access from the container, to the view that is in it. For example the container has a view controller with a textfield and i want to let viewA to know when someone started typing.

I must use delegates, or there is a way to get data from the container view ?

Upvotes: 0

Views: 603

Answers (1)

DBD
DBD

Reputation: 23233

A child UIViewController can access it's parent withparentViewController` and use it to send messages to the parent. You can do this directly, but...

Depending on the level of interaction it might be best to create an interface which the parent UIViewController implements. When the child UIViewController gets added to the parent, it gets a reference to a object implementing the interface. It provides a strong interaction between the objects, but also maintains proper encapsulation, and it is the delegate pattern.

So my answer is, you don't have to use the delegate pattern, but it seems like an appropriate solution. If you don't use the delegate pattern you might find yourself with a pair of objects so heavily coupled you might as well have just made it one object.

// Somewhere in your view controller A you want to add B as a child
B *b = [[B alloc] init]; // create view controller B
b.delegate = self;       // set up A as the delegate to B

// Add B as child
[self addChildViewController:b];
[self.containerView addSubview:b.view];

When B gets added as a child to A the delegate gets set. Assuming A implements an interface, B will have a property like @property (weak, nonatomic) id<MySomethingDelegate> delegate; B should be able to call any delegate method at any point.

Upvotes: 1

Related Questions