Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting default tab in UITabBar in swift

I'm almost finished with a project and am working out the last few UI kinks. My app uses a tab bar to navigate and for aesthetic purposes I want the app to open on the last tab (User Profile) instead of the first. I know I can reorder the tabs in Interface Builder but the tab bar would just look odd having the profile tab first and the home tab anywhere else. How can I leave the profile tab as the 5th tab yet by default open the app on that tab?

like image 683
Nicholas Dill Avatar asked May 04 '15 20:05

Nicholas Dill


People also ask

What is tab bar controller in Swift?

Overview. The tab bar interface displays tabs at the bottom of the window for selecting between the different modes and for displaying the views for that mode. This class is generally used as-is, but may also be subclassed. Each tab of a tab bar controller interface is associated with a custom view controller.


2 Answers

There is a nice way to do this straight from interface builder on your tab bar controller click the identity inspector, and set a User Defined Runtime Attribute.

In this case each index of the tab bar control is indexed like a 0 based array. So the far left is 0, next to the right is 1, then 2 etc...

So in my case I wanted 'tasks' to be selected first, so you set the selectedIndex to type Number and value '1'. Refer to my attached image.

enter image description here

like image 83
Joseph Astrahan Avatar answered Oct 23 '22 11:10

Joseph Astrahan


Just set the selectedIndex of the tabBarController. Something along these lines.

var freshLaunch = true
override func viewWillAppear(animated: Bool) {
     if freshLaunch == true {
         freshLaunch = false
         self.tabBarController.selectedIndex = 4 // 5th tab
     }
}
like image 40
Mark McCorkle Avatar answered Oct 23 '22 10:10

Mark McCorkle