Search code examples
iosswiftuitabbarcontrollertargetuitabbaritem

How do I make a tabbar item available only for a specific target?


I have a tabBarController with three items to different viewControllers. There are four targets in my projects and for one of the targets I would like to add a new tabBar item that goes to newViewController. The item shouldn't show up when I run the other targets.

First I thought it was as easy as setting the newViewController to only be available to the specific target that I wanted, and that it would not show up in the tabBar if I ran the project under a different target. But the app crashed.

Is there a way to hide/show the tabBar item based on target without using the #if target code. We try to get away from that in the project. It would be nice to just do it in the storyBoard if that's possible. If not, then there is a custom tabBar class available. Let me know if you need to see some code from it.


Solution

  • Since the comment section was getting really messy I thought I'd post the gist of how my approach for a different set of UITabBarItem for different target went. So firstly I created a static Environment variable for letting me know which target was getting executed. Here is the code:

    enum Target {
        case targetOne, targetTwo
    
        static var current: Target {
            Bundle.main.bundleIdentifier?.contains("targetOneIdentifier") == true ? .targetOne : .targetTwo
        }
    }
    

    Then inside UITabBarController, I'm setting the viewControllers property according to the current target. This is some code in TabBarController:

    class TabBarController: UITabBarController {
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            let bool = Target.current == .targetOne
            let targetBasedViewController: UIViewController = bool ? FirstViewController() : SecondViewController()
            targetBasedViewController.tabBarItem.title = bool ? "First" : "Second"
            targetBasedViewController.tabBarItem.image = UIImage(named: bool ? "First" : "Second")
        }
    }
    

    Note: This is just the gist of customisation I did. The whole thing is really lengthy and would be really hard to understand considering the scenario.