Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS

Accessing the top view controller in a Navigation Controller

My project has a navigation controller that extends to a view controller, within which another view controller is presented modally. In this last view controller, I am looking to tap a button, dismiss it back down, and send an object back to the first view controller (not the Navigation Controller). The problem is, I can't program a segue directly into my view controller because the Navigation functionality would be left out. And if I program it to go to the Navigation Controller, I can't access the View Controller and its properties from within the prepareForSegue function. Any ideas?

Thanks, Rodrigo

1 Answer

I think this can help. I haven't really used segues during my time with Treehouse, but I have a project of mine in which I constantly need to access a view controller that has a navigation controller embedded into it and here's how I would access the view controller:

      ```Swift
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if segue.identifier == "goToTodoList"{
        let navigationController = segue.destinationViewController as UINavigationController

        let todoListViewcontroller:TodoListViewController= navigationController.topViewController as TodoListViewController

}
     ```

What you have to do is make a variable that points to the UINavigationController in question. In this case I saved it in the "navigationController" variable. Now, I specify the topViewController as TodoListViewController by saying "navigationController.topViewController as TodoListViewController".

I hope this helped.

Regards, Guled

Thank you so much! This was exactly right, I can't believe I missed something so simple..

You deserve more votes btw

Thank you for your kind words Rodrigo. Just remember the more you practice and search online, the more better you'll become. I wish you luck on your endeavor of IOS development.