Lawrence413 Lawrence413 - 8 months ago 35
Swift Question

Access Container Variable From Parent On Event

I have an issue with accessing variables outside a container.

Short Issue: I want to access a container's variable from the view in which is placed when a method executes.

Detailed issue: I have a view and a container imbedded in it. The view's view controller has a countdown timer (say it counts down from 100 to 0 seconds). The timer can pause in certain situations (say when picking an image or song from the library). The container displays some things (not relevant to the issue).

I want to execute a method inside the container's view controller when the parent view controller's number of seconds reaches 0.

Ideally I would want the number of seconds in the container to update when the number of seconds in the parent view update.

But that would mean to access the container's

variable and change it every time I update the number of seconds in the parent view. And I don't know how to do that.

So how do I do that? Is there any way of accessing & modifying a view's variables inside another view's method?


If you've set this up correctly:

  • The embedded view controller is the parent view controller's childViewControllers[0] (or some other index, perhaps, if this parent has multiple embedded view controllers).

  • And vice versa: the parent view controller is embedded view controller's parentViewController.

So the view controllers can readily access one another's members (properties and methods). Configuring each of them with the properties and methods that the other will need access to is up to you. You will need to cast down to the correct UIViewController subclass as you refer to the the other view controller in order to get the compiler to let you access its members.