📱

【iPhone】【Swift】TabBarControllerを実装するサンプルコード

2024/02/12に公開

TabBarControllerを実装するサンプルコード

TabBarController.swift
import UIKit

class TabBarController: UITabBarController {

    override func viewDidLoad() {
        super.viewDidLoad()

        initTab()
    }

    func initTab() {
        let first = UINavigationController(rootViewController: FirstViewController())
        first.tabBarItem = UITabBarItem(title: "FirstVC", image: UIImage(systemName: "house"), selectedImage: nil)

        let second = UINavigationController(rootViewController: SecondViewController())
        second.tabBarItem = UITabBarItem(title: "SecondVC", image: UIImage(systemName: "doc"), selectedImage: nil)

        viewControllers = [first, second]
    }
}
SceneDelegate.swift
import UIKit

class SceneDelegate: UIResponder, UIWindowSceneDelegate {

    var window: UIWindow?


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

        window.rootViewController = TabBarController()
        window.makeKeyAndVisible()
    }

Discussion