[Swift5] Code-only UITabBarController

Main.storyboard is supposed to be deleted.

First, create a class that inherits UITabBarController. Here "TabController"

class TabController: UITabBarController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        var viewControllers = [UIViewController]()
        
        let firstViewController = FirstViewController()
        firstViewController.tabBarItem = UITabBarItem(tabBarSystemItem: .mostRecent, tag: 1)
        viewControllers.append(firstViewController)
        
        let seccondViewController = SeccondViewController()
        seccondViewController.tabBarItem = UITabBarItem(tabBarSystemItem: .mostRecent, tag: 2)
        viewControllers.append(seccondViewController)
        
        let thirdViewController = ThirdViewController()
        thirdViewController.tabBarItem = UITabBarItem(tabBarSystemItem: .mostRecent, tag: 3)
        viewControllers.append(thirdViewController)
        
        self.setViewControllers(viewControllers, animated: false)
        self.selectedIndex = 1
    }
}

Next, set TabController to the initial screen with SceneDelegate.

func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
        guard let _ = (scene as? UIWindowScene) else { return }
        
        guard let windowScene = (scene as? UIWindowScene) else { return }
        let window = UIWindow(windowScene: windowScene)
        self.window = window
        
        window.rootViewController = TabController()
        window.makeKeyAndVisible()
    }

After that, customize FirstVC, SeccondVC, ThirdVC as you like.

Recommended Posts

[Swift5] Code-only UITabBarController