subin272
subin272

Reputation: 753

How to programatically unload a view controller from Tab bar controller?

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
}

Upvotes: 1

Views: 1036

Answers (3)

Milan Nosáľ
Milan Nosáľ

Reputation: 19737

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
}

Upvotes: 2

user8638701
user8638701

Reputation:

if let tabBarController = self.tabBarController {

    let indexToRemove = 3

    if indexToRemove < tabBarController.viewControllers?.count {

        var viewControllers = tabBarController.viewControllers

        viewControllers?.remove(at: indexToRemove)

        tabBarController.viewControllers = viewControllers
    }
}

Upvotes: 0

Indra Mohan
Indra Mohan

Reputation: 465

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
    }

Upvotes: 1

Related Questions