27

I have a view derived from UIViewControler (not UITabBarController). In this view I added a tab bar with several tab bar items. I used the UITabBarDelegate to allow the view to do something when users tap on each tab bar item.

class MyViewController: UIViewController, UITabBarDelegate {

    func tabBar(tabBar: UITabBar, didSelectItem item: UITabBarItem!) {
        // do something
    }
}

My question is how we can programmatically select the first tab bar item when the view is first loaded? Note that I would want the first tab item to be in "active" state also.

Again, I'm not using UITabBarController

Thanks

6 Answers 6

49
[tabBar setSelectedItem: [tabBar.items objectAtIndex:0]];

Which in swift, I think would be:

tabBar.selectedItem = tabBar.items![0] as UITabBarItem
8
  • 2
    Thanks Foster. I actually have to write this code: tabBar.selectedItem = tabBar.items![0] as UITabBarItem However, I would want to simulate the "tap" event on the first tab. Is that possible?
    – tala9999
    Mar 26, 2015 at 19:42
  • I'm not sure what you mean. Are you saying the delegate method tabBar(_:didSelectItem:) isn't called when you do tabBar.selectedItem = tabBar.items![0] as UITabBarItem ? Mar 26, 2015 at 20:06
  • 3
    Yes. That's what I meant. That code just set the tab as "active" and doesn't fire tabBar(_:didSelectItem:)
    – tala9999
    Mar 27, 2015 at 12:13
  • 5
    Directly modifying a tab bar managed by a tab bar controller is not allowed. Got the exception!! What worked for me is: self.tabBarController?.tabBar.selectedItem = 2 Nov 19, 2016 at 7:14
  • 1
    @Foster Bass : calling the tabBar(_:didSelectItem:) method goes against its purpose because this method must be fired automatically by its delegate definition.
    – XLE_22
    Jan 31, 2019 at 9:25
20

Swift 3:

tabBarController.selectedIndex = 0 // (or any other existing index)
6

In swift if tabbar is used not tabbarcontroller set default select

var tabbar:UITabBar?//if declare like this

tabbar!.selectedItem = self.tabbar!.items![0] as? UITabBarItem

or

let tabbar = UITabBar()//if declare and initilize like this

tabbar.selectedItem = self.tabbar.items![0] as? UITabBarItem
1
  • as? UITabBarItem is redundant, at least for newer versions of Swift, and you will get the warning: Conditional cast from 'UITabBarItem' to 'UITabBarItem' always succeeds
    – torof
    Mar 24, 2020 at 7:41
5

if you inside UITabBarController you can useself.selectedIndex = // set target index

0
0

Before select active tab bar item on viewDidLoad event

[self.tabBar setSelectedItem: [self.tabBar.items objectAtIndex:0]];

-1

In Xamarin.ios, we can use like this mainTabBarController.selectedIndex=3;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.