본문 바로가기
Programming/Swift

How to setup UITabBar programmatically

by Eisen Sophie 2021. 6. 6.

left: normal View controller     right: navigation View controller

Set like this in scenedelegate class

func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {

        window?.rootViewController = BaseViewController()
        
        guard let _ = (scene as? UIWindowScene) else { return }
    }

 

You need to make a baseViewController that can hold viewcontrollers.

import UIKit

class BaseViewController: UITabBarController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        viewControllers = [
            createNormal(viewController: ViewController(), tabBarTitle: "Red VC TabBar", backgroundColor: .red),
            createNavViewController(viewController: ViewController(), tabBarTitle: "Orange VC TabBar", navTitle: "Orange", backgroundColor: .orange)
        ]
    }
    
    func createNormal(viewController: UIViewController, tabBarTitle: String, backgroundColor: UIColor) ->UIViewController {
        let vc = viewController
        vc.tabBarItem.title = tabBarTitle
        vc.tabBarItem.image = UIImage(systemName: "r.circle")
        vc.view.backgroundColor = backgroundColor
        return vc
    }
    
    func createNavViewController(viewController: UIViewController, tabBarTitle: String, navTitle: String, backgroundColor: UIColor) -> UIViewController {
        let vc = viewController
        vc.navigationItem.title = navTitle
        vc.view.backgroundColor = backgroundColor
        let navVc = UINavigationController(rootViewController: vc)
        navVc.tabBarItem.title = tabBarTitle
        navVc.tabBarItem.image = UIImage(systemName: "o.circle")
        return navVc
    }

}