Segev
Segev

Reputation: 19303

Open the app in a specific tab in tabbar

I have an app with a TabBar with 5 tabs (regular tab bar with no custom class). When I start the app the left tab is opened. I want it to open the middle one first. I've tried putting

[self.tabBarController setSelectedIndex:3];

in the ViewDidLoad of the ViewController that is first opened but the tab isn't switching. I can see it's highlighted but not selected. If I put the code above under viewWillAppear it will be selected on first run but when I'll select the left tab from time to time it will jump to the middle one.

Also tried this without success:

DetailsViewController* vc = [self.storyboard instantiateViewControllerWithIdentifier:@"DetailsViewController"];
[self.navigationController pushViewController:vc animated:true];    

What Am I doing wrong?

Upvotes: 5

Views: 3392

Answers (6)

bacem
bacem

Reputation: 21

I think if you use tab bar controller you can do those steps. It worked on my project.

  • Create a tab bar controller

  • Create new Cocoatouch Class

  • Write this code:

import UIKit
import Foundation

class CustomTabBarController: UITabBarController {
   
    @IBInspectable var initialIndex = 2

    override func viewDidLoad() {
        super.viewDidLoad()
        
        selectedIndex = initialIndex
    }

}

I chose the 3rd tab bar, but you can change initialIndex as you wish.

Upvotes: -1

Segev
Segev

Reputation: 19303

This is the only solution that worked for me. in appdelegate:

UITabBarController *tabBar = (UITabBarController *)self.window.rootViewController; 
[tabBar setSelectedIndex:2];

Upvotes: 10

Zhang
Zhang

Reputation: 11607

I have done something hackish in the past. I have found in order for each tab to become active, in my applicationDidFinishLaunching, I need to loop through all my view controllers then access the "view" property:

for(viewController in arrayOfViewController)
{
    // will load the view controller into memory
    [viewController view];
}

Don't know if you can make any use of it.

Upvotes: 0

junaidsidhu
junaidsidhu

Reputation: 3580

In storyboard set custom class to the tabbarController and in that custom class

-(void) viewDidLoad
{
    [self.tabBarController setSelectedIndex:3];
}

Upvotes: 1

Rahul Wakade
Rahul Wakade

Reputation: 4805

Try setting it in application:didFinishLaunchingWithOptions: if your tabbar controller is rootViewController like

`[self.window.rootViewController.tabBarController setSelectedIndex:3];`

Upvotes: 0

Misha
Misha

Reputation: 5380

There is a need to call

tabBarController.selectedIndex = desiredIndex;

Inside applicationDidLaunch.

Upvotes: 0

Related Questions