Setting Default Tab in Uitabbar in Swift

Setting default tab in UITabBar in swift

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
}
}

Setting the default tab when using storyboards

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!

How do I set the default tab for tab bar controller in swift

User Omkar responded above with the correct answer. I can successfully switch the first tab using the following viewDidAppear in ThirdViewController.swft

override func viewDidAppear(animated: Bool) {         
self.tabBarController?.selectedIndex = 0
}

Default tab not showing the first tab as selected

IBOutlet weak var tabBar:UITabBar!//and connect this property to the UITabBar in Interface Builder

override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)

if let items = tabBar!.items {
for item in items {
if item.title == "My Tab Title" {
tabBar.selectedItem = item;
}
}
}
}

This works if all tabs have a unique title, which is normally the case.

In swift, how to set initial view for tabBarController

You can do this in your viewDidLoad:

func viewDidLoad (){
self.tabBarController.selectedIndex = 2
}

You select the index when your viewController is loaded. If you want select it only when the user is logged:

func viewDidLoad (){
if userLogged{
self.tabBarController.selectedIndex = 2
}
}

set a default item in a tab bar of type UITabBar (Not UITabBarViewController), in viewDidLoad

Are you sure your tabbar is allocated because self.tabbar?.selectedIndex won't work but neither will crash if your tabbar is nil.

Or have you tried something like this :
self.tabbar.selectedItem = self.tabbar.items![0]
did not test it but maybe it works.



Related Topics



Leave a reply



Submit