Search code examples
iosswiftswift3uitabbarcontrolleruitabbaritem

How to arrange tabbar item at run time in TabBarcontroller?


I have TabBarcontroller with 5 viewcontroller "A", "B", "C", "D", "E". But i need to decide the order at runtime depends on API response. for ex. some time I need to show "A", "D", "C", "E", "B" i.e. in random order, OR sometime i need to show only for "D", "B", "C","A"

is there any way to deal with this scenario?

I am working with Swift 3, but even if i get some logic or possible way it can be helpful to solve my issue.

I have created TabBar and viewcontroller using storyboard.

enter image description here


Solution

  • if  let tabBarController = ( self.window?.rootViewController as? UITabBarController ) {
        if var vcArray = tabBarController.viewControllers {
            //Arrange the array according to your need and set them again.
            tabBarController.viewControllers = vcArray
            //Arrange the array according to your need and set them again.
            var items =   tabBarController.tabBar.items
            tabBarController.tabBar.items = items
        }
    }
    

    You will have to handle selectedViewController. I have written above code in appdelegate but you can get appDelegate's object and use as self in above code.

    Also look at this for another solution where you can create tabCtrl programmatically and manipulate it.