1
votes

I have created a tab bar controller in storyboard, with 5 tab bar items. I want to remove one view controller programatically from the "viewcontrollers" array of the tab bar stack. I also want the app to be show some other tab item as selected when i remove the above view controller. I have tried with the below code, but its not working.

if let tabBarController = self.storyboard?.instantiateViewController(withIdentifier: "tabbar") as? UITabBarController {
    tabBarController.viewControllers?.remove(at: 2)
    tabBarController.selectedIndex = 1
}
3
have you tried asigning a new array of viewControllers that lacks the one you want to remove?Milan Nosáľ
@MilanNosáľ No, i just removed the view controller from the array. Will try that.subin272
@MilanNosáľ Its not working, even though the view controller is getting removed.subin272
try out my updated answerMilan Nosáľ
@MilanNosáľ Tried that now..still not working..has it got something to do with the creation of tab bar in storyboard ?subin272

3 Answers

2
votes

Reassign viewControllers property without the one you don't want:

if let tabBarController = self.storyboard?.instantiateViewController(withIdentifier: "tabbar") as? UITabBarController {
    tabBarController.selectedIndex = 1
    var controllers = tabBarController.viewControllers
    controllers.remove(at: 2)
    tabBarController.viewControllers = controllers
}

Now this code is ok, but the problem is the following line:

let tabBarController = self.storyboard?.instantiateViewController(withIdentifier: "tabbar") as? UITabBarController

This creates a new UITabBarController instance - but you want to access the one that was instantiated by the storyboads and that is presented on the screen. However, without more context it's hard to give you suggestions on how to access it. Considering that you call this code from a viewController directly embedded in the tab bar controller, I would start with this:

if let tabBarController = self.tabBarController {
    tabBarController.selectedIndex = 1
    var controllers = tabBarController.viewControllers
    controllers.remove(at: 2)
    tabBarController.viewControllers = controllers
}
1
votes

Try this:

    if let tabBarController = self.storyboard?.instantiateViewController(withIdentifier: "tabbar") as? UITabBarController {
        var viewControllers = tabBarController.viewControllers
        viewControllers.remove(at: 2)
        tabBarController.viewControllers = viewControllers
        tabBarController.selectedIndex = 1
    }
0
votes
if let tabBarController = self.tabBarController {

    let indexToRemove = 3

    if indexToRemove < tabBarController.viewControllers?.count {

        var viewControllers = tabBarController.viewControllers

        viewControllers?.remove(at: indexToRemove)

        tabBarController.viewControllers = viewControllers
    }
}