I have a tabBar with a tab that contains a NavVC that has a root as a ParentVC. The ParentVC has a segmentedControl that manages two childVCs, RedVC and BlueVC. Both the RedVC and BlueVC contain a button to push on a YellowVC.
The issue is when the YellowVC gets pushed on, and in it's viewDidLoad I check to see the view controllers on the stack, the two controllers that appear are the ParentVC and the YellowVC, there is no mention of either The RedVC (if it pushes it on) or the BlueVC (if it pushes it on).
for controller in navigationController!.viewControllers {
print(controller.description) // will only print ParentVC and YellowVC
}
I understand that since the tabBar has a navVC as it's tab and it's root is the ParentVC then that's the root of the push but I need to know which one of either the RedVC or the BlueVC triggered it when the YellowVC gets pushed on.
I can use some class properties in the YellowVC but I want to see if there's another way via the navigationController:
var pushedFromRedVC = false // I'd prefer not to use these if I don't have to
var pushedFromBlueVC = false
How can I get a reference to the RedVC or BlueVC when either of them push on the YellowVC?
class MyTabBarController: UITabBarController {
override func viewDidLoad() {
super.viewDidLoad()
let parentVC = ParentVC()
let navVC = UINavigationController(rootViewController: parentVC)
navVC.tabBarItem = UITabBarItem(title: "Parent", image: nil), tag: 0)
viewControllers = [navVC]
}
}
class ParentVC: UIViewController {
var segmentedControl: UISegmentedControl! // switching segments will show either the redVC or the blueVC
let redVC = RedController()
let blueVC = BlueController()
override func viewDidLoad() {
super.viewDidLoad()
addChildViewController(redVC)
view.addSubview(redVC.view)
redVC.didMove(toParentViewController: self)
addChildViewController(blueVC)
view.addSubview(blueVC.view)
blueVC.didMove(toParentViewController: self)
}
}
class RedVC: UIViewController {
@IBAction func pushYellowVC(sender: UIButton) {
let yellowVC = YellowVC()
yellowVC.pushedFromRedVC = true // I'd rather not rely on this
navigationController?.pushViewController(yellowVC, animated: true)
}
}
class BlueVC: UIViewController {
@IBAction func pushYellowVC(sender: UIButton) {
let yellowVC = YellowVC()
yellowVC.pushedFromBlueVC = true // I'd rather not rely on this
navigationController?.pushViewController(yellowVC, animated: true)
}
}
class YellowVC: UIViewController {
var pushedFromRedVC = false // only sample, I'd rather not use these if I don't have to
var pushedFromBlueVC = false
override func viewDidLoad() {
super.viewDidLoad()
for controller in navigationController!.viewControllers {
// even though the push is triggered from either the RedVC or BlueVC it will only print ParentVC and YellowVC
print(controller.description)
}
}
}