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
Might seem like overkill for some to subclass UITabBarController
, but, I think it provides the cleanest solution.
BaseTabBarController.swift
Add an @IBInspectable
and set it in viewDidLoad
:
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:
Building upon Aviel Gross' answer, I just wanted to implement this for a UITabBar, as opposed to a UITabBarController. This can be done as follows:
class BaseTabBar: UITabBar {
@IBInspectable var defaultIndex: Int = 0 {
didSet {
self.selectedItem = self.items?[defaultIndex]
}
}
}
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.
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:
This should be what it looks like when you've achieved the above steps:
In InterfaceBuilder, disconnect all the segues, then reconnect them in the order you want them to appear.
My variant is suitable when you want just change the default selected controller, no more customizing. Just add the follow category:
// UITabBarController+DefaultPage.h
#import <UIKit/UIKit.h>
@interface UITabBarController(DefaultPage)
@end
// UITabBarController+DefaultPage.m
#import "UITabBarController+DefaultPage.h"
@implementation UITabBarController(DefaultPage)
- (void)viewDidLoad {
[super viewDidLoad];
self.selectedIndex = 1;
}
@end
p.s: I prefer @joshua-finch answer