Setting the default tab when using storyboards
Solution 1
You can use one of these two methods:
tabBar.items = tabBarItems;
tabBar.selectedItem = [tabBarItems objectAtIndex:0];
or a direct method from the object
[tabBar setSelectedItem:myUITabBarItem];
or you can combine them to do this:
tabBar.items = tabBarItems;
[tabBar setSelectedItem:[tabBarItems objectAtIndex:0]];
but i havent tested that method yet, hope this helps!
Solution 2
Whilst you can set the initial selected tab programmatically like the other answers, to achieve the same in your storyboard without touching code you would perform the following:
- Select the Tab Bar Controller in the Storyboard Interface
- Show the Identity Inspector in the Utilities panel
- Add a new "User Defined Runtime Attribute"
- Set the Key Path to "selectedIndex"
- Set the Type to "Number"
- Set the Value to the index of the tab you wish to select (a value of 1 would select the second tab for example)
- Save the Storyboard, build and run the application
This should be what it looks like when you've achieved the above steps:
Solution 3
Might seem like overkill for some to subclass UITabBarController
, but, I think it provides the cleanest solution.
- Create
BaseTabBarController.swift
Add an
@IBInspectable
and set it inviewDidLoad
:class BaseTabBarController: UITabBarController { @IBInspectable var defaultIndex: Int = 0 override func viewDidLoad() { super.viewDidLoad() selectedIndex = defaultIndex } }
In the storyboard, set you
UITabBarController
to be your new subclass:
- Go to the Attributes Inspector add set the new property Default Index:
- ta-da! (:
Solution 4
- Create a new file subclass of
UITabBarController
; Add this at the end of
viewDidLoad
:self.selectedIndex = 1;
Set this new file as the Custom Class in the
UITabBarController
of your Storyboard.
You're done.
Solution 5
The following code worked for me:
UITabBarController *tabBarController = (UITabBarController *)self.window.rootViewController;
tabBarController.selectedIndex = 2;
user1145581
Updated on June 22, 2020Comments
-
user1145581 about 4 years
Can anyone please tell me how to set the default tab when using storyboards in iOS. I can't seem to figure out how to accomplish this.
Thank you