Search code examples
iosswiftuitabbarcontrolleruitabbartvos

SWIFT: If I implement the UITAB bar programmatically, is it possible to edit the different tabItems inside the storyBoard


I have implemented a tabBar programmatically:

class ViewController: UIViewController {
     let tabBarCnt = UITabBarController()
    override func viewDidLoad() {
        super.viewDidLoad()
         tabBarCnt.tabBar.tintColor = UIColor.black
         createTabBarController()
    }
    func createTabBarController() {
        let firstVc = UIViewController()
        let downloadViewController = DownloadsViewController()
        downloadViewController.tabBarItem = UITabBarItem(tabBarSystemItem: .downloads, tag: 0)
        let bookmarkViewController = BookmarksViewController()
        bookmarkViewController.tabBarItem = UITabBarItem(tabBarSystemItem: .bookmarks, tag: 1)
        let favoritesViewControllers = FavoritesViewController()
        favoritesViewControllers.tabBarItem = UITabBarItem(tabBarSystemItem: .favorites, tag: 2)
       
        // Adding navigationControllers
        let controllerArray = [downloadViewController, bookmarkViewController, favoritesViewControllers]
        // For somereason this made the word Home appear in first tab
        tabBarCnt.viewControllers = controllerArray.map{ UINavigationController.init(rootViewController: $0)}
        self.view.addSubview(tabBarCnt.view)
    }
}

DownloadViewController.swift

class DownloadsViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.green
        self.title = "Downloads"
    }
}

This is the result: enter image description here

MY QUESTION IS: Do I have to implement all the layouts of the different viewControllers downloadViewController, bookmarkViewController, favoritesViewControllers programmatically?
Can't I use the storyboard and associate a viewController and do all the UI design and implementation there like this:
enter image description here

enter image description here

The problem here is that if I will implement all the layout programmatically, it won't be an obvious or a practical thing to do.

And assigning DownloadsViewController to that storyboard ViewController, doesn't make it get display it when I navigate to DownloadsTab in the UITabBar.


Solution

  • Yes, you can do that currently your creating view controller instance programmatically, instead of that you have to load/get viewController instance from storyBoard like this.

    UIStoryboard(name: "Main", bundle: Bundle.main).instantiateViewController(identifier: "downloadsVC") as! DownloadsViewController
    

    before calling this method set viewController StoryboardIDenter image description here