Select a tab bar item programmatically (not using UITabBarController)

妖精的绣舞 提交于 2020-05-26 10:16:46

问题


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


回答1:


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

Which in swift, I think would be:

tabBar.selectedItem = tabBar.items![0] as UITabBarItem



回答2:


Swift 3:

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



回答3:


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



回答4:


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




回答5:


Before select active tab bar item on viewDidLoad event

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




回答6:


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



来源:https://stackoverflow.com/questions/29286683/select-a-tab-bar-item-programmatically-not-using-uitabbarcontroller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!