Reputation: 2162
hi I am new to ios development particularly in swift. Basically I just need to switch tab, I have tried tabBarController?.selectedIndex = 1
but it seem not to switch tab.
the image above is my story board, the initial set up is I have splitview controller the initial view that is on master is tableViewController
which is A
and when tapped on the accessory of cell the detail which is detail of A
appear on detail of splitview and when tapped on row itself
the Tab Bar Controller
replace the master
then I have four tabs in my tabBarController Tab B
, Tab C
, Tab D
, and Tab E
which is just a list when tapped it shows its respective view controller as detail of splitview then in my tab E
I have 3 buttons each button designed to function to switch tab
note: the tabs and details are embedded in navigation controller
I'm a bit confuse on how and what is the standards for this. Could anyone help me any comment, suggestion would do.
Upvotes: 2
Views: 17200
Reputation: 239
In the identity inspector of the tab bar controller, I added a name to the storyboard ID "tabBarController". Within my action I add instantiate the view controller and cast UITabbarController. You'll be able to switch to the tab bar you selected. Hope this helps
@IBAction func buttonTapped(_ sender: Any) {
let mainStoryboard = UIStoryboard(name: "Main", bundle: Bundle.main)
let vc: UITabBarController = mainStoryboard.instantiateViewController(withIdentifier: "tabBarController") as! UITabBarController
vc.selectedIndex = 0
self.present(vc, animated: true, completion: nil)
}
Upvotes: 5
Reputation: 51
add in your AppDelegate.swift: var tabBarController: UITabBarController?
and then you can put in another Controller self.tabBarController!.selectedIndex = 0
worked for me
Upvotes: 2
Reputation: 4934
The reason for
tabBarController?.selectedIndex = 1
is not working, is that tabBarController is nil.
In order to get the right tabBarController, you will have to get it from the root of window object. Something like this,
var tabBarController: UITabBarController = self.window?.rootViewController as? UITabBarController tabBarController.selectedIndex = 1
Since, you might have to find right tabBarController in your navigation stack, you will have to traverse stack as well. From the storyboard above, I believe you are loading tabbarController from a Tableview didSelect, so you will have to get tabBarController there and select tabbar index there.
Hope it helps.
Upvotes: 9