0

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)
Taras Tomchuk
  • 331
  • 7
  • 19

1 Answers1

1

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.

えるまる
  • 2,409
  • 3
  • 24
  • 44
  • 2
    Thanks for answer. Your solution didn't quite work for me, but put me on correct path. I came up with this: `if let tabBarController = appDelegate.window!.rootViewController as? UITabBarController { }` and it allows me to get access to my TabBarController anywhere in code. Thanks! – Taras Tomchuk Sep 14 '19 at 10:11