Search code examples
iosswiftuitabbarcontrolleruitabbaruitabbaritem

Switch TabBar Item from separate Navigation Controller


In my application I have TabBar Controller and Navigation Controller with one View Controller that are not connected to each other.

I use TabBar Controller as root vc in my app, and other Navigation Controller as a side menu which slides in on top of TabBar Controller. To make menu I used this repo - SideMenu

Question: How can I switch TabBar item from that Menu I have? Simply calling tabBarController?.selectedIndex = 1 inside MenuViewController does nothing.

What I have done so far:

  • As a temporary working solution I have used Notification Center to register switching of tabs in my ViewController that is presented by TabBar Controller, but I don't think this is great idea, as I have 5 VC in it and only in one of them I have func that switches tabs.
  • Calling TabBar by Storyboard ID and then working with it also didn't help.
  • Extending UITabBarController class also didn't help (possibly did smth wrong)

Solution

  • In my app I have MainTabBarController which is almost always is root. I use static variable to access shared one.

    class MainTabBarController: UITabBarController, UITabBarControllerDelegate {
        // MARK: - Variables
        public static var shared: MainTabBarController? {
            set {
                UIApplication.shared.window.rootViewController = newValue
            }
    
            get {
                guard let mainTabBarController = UIApplication.shared.window.rootViewController as? MainTabBarController else { return nil }
    
                return mainTabBarController
            }
        }
    }
    

    So I can change it any time.

    MainTabBarController.shared?.selectedIndex = 0
    

    Simply calling tabBarController?.selectedIndex = 1 inside MenuViewController does nothing.

    This shouldn't work, because of your hierarchy.