Search code examples
iosswiftxcodeuitabbarcontrolleruitabbar

Change the destination View Controller of a tab in a Tab Bar


I really like to know how can I change the link/destination ViewController for a tab bar item in swift.

My case:

if (beforeDayX)
{
    //TabBar[0] (Home) shows my1Scene with my1ViewController 
} else
{
    // TabBar[0] (Home) shows my2Scene with my2ViewController 
}

How should I do that? Is it possible to do?


Solution

  • Note: Initial answer was creating tabBar programmatically. But since the Josep (the questioner) already have the tabBar created via Storyboard, I change the answer here to suit the need.

    Assumptions:

    (1) TabBar was created using UITabBarViewController. Class name: TabBarViewController

    (2) Initially, the Tabbar consist of WeekendVC, WeekdayVC, OtherVC.

    (3) Based on condition the Tabbar will either become: ( WeekendVC and OtherVC ) or (WeekdayVC and OtherVC ) only.

    Here is what the TabBarViewController will look like:

    import UIKit
    
    enum TypeOfDay {
        case weekday
        case weekend
    }
    
    class TabBarViewController: UITabBarController {
    
        var typeOfDay: TypeOfDay = .weekday
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            // Initial order is: WeekendVC, WeekdayVC, OtherVC
            if let currentViewControllers = self.viewControllers {
    
                let weekendVC = currentViewControllers[0]
                let weekdayVC = currentViewControllers[1]
                let otherVC = currentViewControllers[2]
    
                switch typeOfDay {
                case .weekend:
                    self.viewControllers = [weekendVC, otherVC]
                case .weekday:
                    self.viewControllers = [weekdayVC, otherVC]
                }
            }
        }
    }