Tim Dietrich

Custom Software Developer

Home Services Portfolio Blog About Contact Newsletter

Swift: Programmatically Removing Tabs From A TabBarController

I ran into something new today with regards to Swift. Actually, that seems to happen every day!

I'm working on app that uses a TabBarController, and there are times when some of the tabs aren't applicable. The app displays restaurant info, including the details (rating, cuisine, etc), photos, and scanned PDFs of the menu. However, there are some restaurants for which photos and/or the menu isn't available from the database.

So my goal was to programmatically hide the tabs that didn't apply. Here's the working code...

class ViewControllerTabs: UITabBarController {
    override func viewDidLoad() {
        // Set the title to the restaurant name.
        self.title = selectedRestaurant["Name"] as? String
        // Remove any tabs that aren't applicable for this restaurant.
        var tabBarViewControllers = self.viewControllers
        if selectedRestaurant["Menu"] == nil {
        if selectedRestaurant["Pictures"] == nil {

        self.setViewControllers(tabBarViewControllers, animated: true)

This is the class for the TabBarController. As you can see, I'm taking its array of view controllers, removing any controllers that aren't applicable, and then replacing the view controllers. The trick is to remove the unnecessary view controllers from right to left, so that an "Array index out of range" error is avoided.

I've seen other approaches to solve this problem, but I think this approach is much cleaner, and gives you better control.