Fil Fil - 4 months ago 10
iOS Question

UIViewController no longer has members topViewController or viewControllers in XCode 7

After updating to XCode 7 and converting my project to the latest Swift 2 syntax, there is one error I cannot seem to fix. I have a segue to a navigation controller and need to pass data to the top view controller in its stack. The following has always worked until now:

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
let destinationVC = segue.destinationViewController.viewControllers[0] as! MYViewController
// OR let destinationVC = segue.destinationViewController.topViewController as! MYViewController
// ...
}


But now the compiler gives error:

Value of type 'UIViewController' has no member 'viewControllers'

or
Value of type 'UIViewController' has no member 'topViewController'


I do not see how else to access the view controller(s) on the stack. Any ideas? Thanks in advance!

Answer

Add as! UINavigationController after segue.destinationViewController so that to cast to UINavigationController class type.

let destinationVC = (segue.destinationViewController as! UINavigationController).viewControllers[0] as! MYViewController

Or

let destinationVC = (segue.destinationViewController as! UINavigationController).topViewController as! MYViewController
Comments