Marko Zadravec
Marko Zadravec

Reputation: 8730

Best way to find the element in view hierarchy

I would like to know how you navigate to a higher level views in your UIViewController stack, if you need to change something on them.

One of the example is if you have TabViewController and you need to communicate between tabs, but this is not the only case.

What I do now is something like this

let tabOne = self.tabBarController?.childViewControllers.first?.childViewControllers.first as? tabOneController

or

let topController = ((self.viewControllers[0] as! RootViewController).viewControllers![0] as! UINavigationController).topViewController as? MySpecialViewController

Problem with this approach is that you really need to know hierarchy of the view, you havely depend on it, and you need to change it if you change hierarchy a little bit.

Second problem is, if you are working in a team, that this code is very frustrating and not descriptive enough for other team members.

My question is, what is the right approach / best practice, or : how you do this?

Upvotes: 1

Views: 552

Answers (1)

Lou Franco
Lou Franco

Reputation: 89142

A very common idiom in iOS is for the tab controller to provide a delegate interface and for the top controller to pass it an implementation. A simple way is to have the top controller actually implement it itself.

In that solution, tabOne does not have any idea that it is in a tab controller -- it just calls its delegate methods. The tab controller does whatever is necessary.

Upvotes: 1

Related Questions