I want to pass information from a ViewController
to a UITabBarController
so that I can access certain information from the view controller in the 3rd tab of the UITabBarController
.
However, the issue is my program keeps crashing when I try to do so. Here is my code so far:
I call the segue like so:
self.firstName = user.first_name
self.lastName = user.last_name
self.performSegueWithIdentifier("OffersView", sender: self)
And I override the prepareForSegue
function so that I can pass information in this function like so:
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if(segue.identifier == "OffersView"){
let barViewControllers = segue.destinationViewController as UITabBarController
let destinationViewController = barViewControllers.viewControllers![2] as ProfileController
destinationViewController.firstName = self.firstName
destinationViewController.lastName = self.lastName
}
}
When I try to set the destinationViewController
(on the second line in the code above), my code crashes. I'm not sure why as I've looked on numerous StackOverflow posts such as
Swift tab bar view prepareforsegue and Pass data from tableview to tab bar view controller in Swift. but have not have much success. Do I possibly need to create a UITabBarControllerDelegate
class and pass information through that? Any tips would be appreciated. Thanks!
The problem, as discovered after a discussion, was that the tab bar controller's children were embedded in navigation controllers, so the code needed to be changed to this,
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
let barViewControllers = segue.destinationViewController as! UITabBarController
let nav = barViewControllers.viewControllers![2] as! UINavigationController
let destinationViewController = nav.topviewcontroller as ProfileController
destinationViewController.firstName = self.firstName
destinationViewController.lastName = self.lastName
}
In swift 3, xcode 8 that code would be like
let barViewControllers = segue.destination as! UITabBarController
let nav = barViewControllers.viewControllers![0] as! UINavigationController
let destinationViewController = nav.viewControllers[0] as! YourViewController
destinationViewController.varTest = _varValue
Swift 4 solution without force optional unwrapping
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let barVC = segue.destination as? UITabBarController {
barVC.viewControllers?.forEach {
if let vc = $0 as? YourViewController {
vc.firstName = self.firstName
vc.lastName = self.lastName
}
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With