Sahil Manchanda
Sahil Manchanda

Reputation: 10547

Select tab programmatically custom tab bar ios

I have used the following tutorial to implement custom tabs in ios Its working fine when i tap on any of the item. Now I want to move it Programatically. e.g. I received the notification form Firebase and want to open third tab. But I am getting nil. I have referenced the MainTabbarController instance in appdelegate. Here is what i have tried In CustomTabBar

func customTapped(index :Int){
        animateTabBarSelection(from: selectedTabBarItemIndex, to: index)
        selectedTabBarItemIndex = index
        delegate.didSelectViewController(self, atIndex: index)
}

In AppDelegate

mainTabBarController?.customTabBar?.customTapped( index: 2)

Upvotes: 2

Views: 807

Answers (1)

Aravind A R
Aravind A R

Reputation: 2714

From the link that you have provided along with the question, the following are the statements that I found to be responsible for switching the tabs

func barItemTapped(sender : UIButton) {
    let index = tabBarButtons.indexOf(sender)!

    animateTabBarSelection(from: selectedTabBarItemIndex, to: index)
    selectedTabBarItemIndex = index
    delegate.didSelectViewController(self, atIndex: index)
}

You can just modify this code as

func barItemTapped(sender : UIButton) {
    let index = tabBarButtons.indexOf(sender)!
    tabSelectedAt(index)

}

func tabSelectedAt(_ index:Int) {
 if selectedTabBarItemIndex != nil {
   animateTabBarSelection(from: selectedTabBarItemIndex, to: index)
  }
    selectedTabBarItemIndex = index
    delegate.didSelectViewController(self, atIndex: index)
}

So call the function func tabSelectedAt(_ index:Int) with the index of the tab which you wants to switch.

Upvotes: 1

Related Questions