问题
On photo below I show you my storyboard. On TableView Controller I have expandable menu. What I cannot achieve right now is to switch on second tab bar item (green one) and let it know what is ID of selected menu item. Between tab bar controller and green and blue controllers I have relationship "view controllers". I tried to call directly green view controller with this code:
let secondTab = self.storyboard?.instantiateViewController(withIdentifier: "secondstoryboardid") as! SecondVC
self.present(plavi, animated: true, completion: nil)
This code displays second tab view but without tab bar and everything derived from container view.
回答1:
If you configured correctly such storyboard, you should get the reference to the UITabBarController
through prepare(segue)
, doing so:
private weak var tabBarViewController:UITabBarController?
// be sure to add prepare inside your segue manager (the container in this case)
override public func prepare(for segue: UIStoryboardSegue, sender: Any?) {
self.tabBarViewController = segue.destination as? UITabBarController
}
besides you may want to declare an enum to have a clean access to the embedded view controllers:
enum TabType:Int {
case blue
case green
}
thus you might define a function for injecting the selected indexPath, doing something like:
func inject(indexPath:IndexPath, into tab:TabType) {
if let greenVc = tabBarViewController?.viewControllers?[tab.rawValue] as? GreenViewController {
greenVc.selectedIndexPath = indexPath
tabBarViewController?.selectedIndex = tab.rawValue // this will auto select the TabType viewcontroller
}
}
finally whenever you have to change the current selection, you may call inject with the new indexPath:
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
self.inject(indexPath: indexPath, into: .green)
}
Note
Call instantiateViewController
means making a new "fake" view controller, which is a wrong approach, since you already have it embedded in your UITabBarController.viewControllers
来源:https://stackoverflow.com/questions/48413163/pass-data-to-tab-bar-item-viewcontroller