I have the following Storyboard layout:
When the app starts it goes to HomeView VC at TabIndex 1.
In the HomeView I have a but
To go from TestView to HistoryView, should be something along these lines:
// From TestView to HomeView(0)
navigationController?.popViewController(animated: true)
// Change the active tab in the tabcontroller
(navigationController?.presentingViewController as? UITabBarController)?.selectedIndex = 1
Set up your HomeViewController like this:
class HomeViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
var goToHistory = false
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if goToHistory {
goToHistory = false
// Use whichever index represents the HistoryViewController
self.tabBarController?.selectedIndex = 1
}
}
@IBAction func unwindAndGoToHistory(_ segue: UIStoryboardSegue) {
goToHistory = true
}
}
In your TestViewController, either:
Wire a UIButton to the Exit icon to unwind to unwindAndGoToHistory:.
OR
Create a programmatic unwind by wiring from the View Controller icon to the Exit icon (again selecting unwindAndGoToHistory:), and then find this segue in the Document Outline view and give it an identifier such as "unwindToHistory" in the Attributes Inspector. When you're ready to segue, trigger it with performSegue(withIdentifier: "unwindToHistory", sender: self).
Then, when the unwind segue is triggered, iOS will pop the TestViewController and call unwindAndGoToHistory(). In there, goToHistory gets set to true. Afterwards, viewWillAppear() will be triggered. Since goToHistory is now true, the code will set the selectedIndex of the tabBarController to switch to the HistoryViewController's tab.
Note: This will show the unwind animation back to
HomeViewController, then the view will automatically switch toHistoryViewController. If instead you'd like to switch toHistoryViewControllerimmediately with no animation, overrideviewWillAppearinstead ofviewDidAppear.