UITabBarController - How to switch to the tab of a particular type

advertisements

I have a UITabBarController implemented by a custom class (eg HomeTabBarController) and in my storyboard I've attached to it 3 ViewController as it's child.

I know that I can use, in order to select a particular view controller, in my UITabBarController:

selectedIndex = 2

But I would like to make my project a bit more flexible, so I would like to select a child tab only knowing it's type, not it's position. How can I do it?


As described in the StackOverflow documentation I'm going to answer my own question.

Let's make an example, you have a UITabBarController with 3 childs:

  • HomeTabBarController

    • CustomAViewController
    • CustomBViewController
    • CustomCViewController

In your HomeTabBarController controller you can put a func as this:

func selectCustomATab()    {
    var tab = 0

    for v in viewControllers!   {
        for k in v.childViewControllers {
            if k is CustomAViewController  {
                tab = viewControllers!.indexOf(v)!
            }
        }
    }

    selectedIndex = tab
}

And that's all, you can repeat for every ViewController child as you like.

Then in any ViewController child you can do something like that in order to switch tab:

(self.tabBarController as! HomeTabBarController).selectCustomATab()

Completely ignoring what's the CustomAViewController position in the tab array.