Search code examples
iosswiftuitabbarcontroller3dtouch

Unable to change tab using self.tabBarController?.selectedIndex


My application is embedded within a TabBarController, I am trying to switch the selected tab from the ViewController.

With the following few lines I was hoping to find out if the function worked, unfortunately it does not but I am unsure why, can anybody help out where I am going wrong ?

func tabbar() { self.tabBarController?.selectedIndex = 4 }

override func viewDidLoad() {
    super.viewDidLoad()
    tabbar()

}

PS: The reason I am testing this is because I wanted to find out if the following will work for my 3DTouchShortcuts. I know the 3D Touch Shortcuts appear and open the initial view controller, I am hoping the following line for each case would actually make the shortcut open to different tabs.

tababarController.selectedIndex = 1

private func handleShortcutItem(shortcutItem: UIApplicationShortcutItem) {

     if let rootViewController = window?.rootViewController, let shortcutItemType = ShortcutItemType(shortcutItem: shortcutItem) {
        let tabbarController = rootViewController as! UITabBarController

        switch shortcutItemType {
        case .AddItem:
            NSNotificationCenter.defaultCenter().postNotificationName("performsegueAddItem", object: nil)
            tabbarController.selectedIndex = 1
            break
        case .FavouritesTab:
            tabbarController.selectedIndex = 2
            break

        }
    }
}

Solution

  • You just have to call it inside viewDidLayoutSubviews instead of viewDidLoad and you should use tabBarController when calling it. You should also use guard to unwrap it:

    override func viewDidLayoutSubviews() {
        guard let tabBarController = tabBarController else { return }
        tabBarController.selectedIndex = 0
    }