Bijan Cronin
Bijan Cronin

Reputation: 101

Replace one of the view controllers of tab bar controller

I'm working on an application that uses a UITabBarController and I've assigned 3 ViewControllers to the UITabBarController.

I'm building this application programmatically. In AppDelegate I created a UITabBarController. I then create a UINavigationController and set the rootViewController as the UITabBarController.

I then set window rootViewController as the UINavigationController

Here's my code from AppDelegate:

    let mainViewcontroller = TabBarController()
    let navigationController = UINavigationController(rootViewController: mainViewcontroller)
    self.window = UIWindow(frame: UIScreen.main.bounds)
    self.window!.rootViewController = navigationController
    self.window?.makeKeyAndVisible()

Now I created instances of my 3 viewControllers and added them to the viewController list of the UITabBarController. What I want to do now is to display on tap of a button a new different viewController that is not one of the 3 viewControllers that are assigned to the TabBar. I have been able to achieve this by using the present(ViewController) method:

    newVC = UINavigationController(rootViewController: NewViewController())
    self.present(newVC, animated: true, completion: nil)

The problem that I'm having is that I want the viewController to be displayed behind the UITabBarController. When I use the present() from above the viewController is displayed over the viewController and the TabBar. I've tried presenting the viewController by doing self.tabBarController.present() and window.rootViewController.present and I get the same result which is the TabBar is gone. I would appreciate any suggestions. Thanks

Upvotes: 1

Views: 3072

Answers (1)

Chetan Koli
Chetan Koli

Reputation: 188

I have created a custom Tab bar which is a subclass of UITabBarController in my application. It has the following functionality for handling a scenario like yours.

UITabBarController holds an array of its child view controllers. Required (external) view controller is replaced with a currently visible view controller, which is at the selected index of UITabBarController, of that array. Then this updated array is set back to UITabBarController's child view controller array

func setSelectedViewController(_ externalViewController: UIViewController) {

    var arrChildViewControllers = self.childViewControllers

    if arrChildViewControllers.count > 0 {

        let selectedTabIndex = self.selectedIndex
        arrChildViewControllers.replaceSubrange(selectedTabIndex...selectedTabIndex, with: [externalViewController])

        self.viewControllers = arrChildViewControllers
    }

}

Upvotes: 1

Related Questions