Search code examples
iosswiftuitabbarcontrolleruitabbaritem

Unable to see controller added to UITabBar programmatically swift


I added 2 tabBar items from storyboard and one UITabBarItem - Menu programmatically. I am successfully able to open the controllers corresponding to tabBarItems which I created using storyboard. However, when I click on "Menu" a blank black screen appears,

@objc public class MainScreenTabsController : UITabBarController {
public override func viewDidLoad() {
    super.viewDidLoad()
    let tabController = MyViewController()
    let tabBarItem = UITabBarItem(title: "Menu", image: UIImage(named: "more-options.png"), selectedImage: UIImage(named: "more-options"))
    tabController.tabBarItem = tabBarItem
    var array = self.viewControllers
    array?.append(tabController)
    self.viewControllers = array
}

public func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
    return true;
}

public override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
}
}

I followed couple of tutorials for adding tab bar item but all of them had the code I wrote. Am I missing out something very basic? The three dots represent menu. The word menu is not included because in the real code I gave a blank string

EDIT:

Class for Menu Controller

@objc public class MyViewController:UIViewController {

public override func viewDidLoad() {
    super.viewDidLoad()
}

public override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
}
}

Solution

  • Your app is doing exactly what your code is telling it to do. You are creating an instance of MyViewController and adding it to the UITabBarController's array of View Controllers.

    Your MyViewController class file simply defines a blank, black view.

    I'm guessing you created a ViewController in your Storyboard that you want to use as MyViewController? If so, you need to instantiate that from the storyboard.

    When you're editing your storyboard, assign the MyViewController class to the VC you want to use, and also give it a Storyboard ID - such as MyVC. Then, edit your viewDidLoad function to this:

    public override func viewDidLoad() {
        super.viewDidLoad()
    
        // wrong way
        //  let tabController = MyViewController()
    
        if let tabController = storyboard?.instantiateViewController(withIdentifier: "MyVC") as? MyViewController {
    
            let tabBarItem = UITabBarItem(title: "Menu", image: UIImage(named: "more-options.png"), selectedImage: UIImage(named: "more-options"))
            tabController.tabBarItem = tabBarItem
            var array = self.viewControllers
            array?.append(tabController)
            self.viewControllers = array
    
        }
    
    }