问题
I have the following Storyboard layout:
When the app starts it goes to HomeView VC at TabIndex 1.
In the HomeView I have a button and I segue to the TestView using
performSegue(withIdentifier: "goToStartTest", sender: self)
Now I want to go from TestView to HistoryView. The only way I can see to do that right now is to create a segue from TestView to TabBarController. This brings up HomeView with Tab Bar intact. I do this from TestView using
performSegue(withIdentifier: "testToRes", sender: self)
However, that leaves me on HomeView, I need HistoryView.
The research I've done points to using Unwind and detecting where segue came from and acting accordingly.
I'm using the latest Xcode with Swift 5.
回答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
UIButtonto theExiticon to unwind tounwindAndGoToHistory:.OR
Create a programmatic unwind by wiring from the
View Controllericon to theExiticon (again selectingunwindAndGoToHistory:), 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 withperformSegue(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.
回答2:
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
来源:https://stackoverflow.com/questions/56032435/unwind-from-a-vc-to-a-tabbarcontroller-and-change-tab-index