LoginSignup
0
0

Storyboardをつかわない、UITabBarControllerをルートとしたのプロジェクト作成

Last updated at Posted at 2024-05-15

はじめに

タブバーからのアプリの立ち上げ方メモ
今回のサンプルリポジトリ

できるもの

2つのタブバーで画面きりかえをする。

ストーリーボードを使用しない設定をする

以下記事を参考にしてください。

ViewControllerを2つ作成

下記のようなViewControllerを作成します。

import UIKit

class HogeVC: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .systemRed
    }
}
import UIKit

class FugaVC: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .systemBlue
    }
}

SceneDelegate修正

下記修正を追加します。

    func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
            //UIwindowsのアンラップ
            guard let scene = (scene as? UIWindowScene) else { return }
            // window生成
            let window = UIWindow(windowScene: scene)
            // ルートビュー指定
            window.rootViewController = createTabbar()
            // キーウインドウ指定
            window.makeKeyAndVisible()
            // windowインスタンスが解放されないようにパラメータに代入する
            self.window = window

            configureNavigationBar()
        }

    func createHogeNC() -> UINavigationController {
        let hogeVC = HogeVC()
        hogeVC.title = "Hoge"
        hogeVC.tabBarItem = UITabBarItem(tabBarSystemItem: .bookmarks, tag: 0)

        return UINavigationController(rootViewController: hogeVC)

    }

    func createFugaNC() -> UINavigationController {
        let fugaVC = FugaVC()
        fugaVC.title = "Fuga"
        fugaVC.tabBarItem = UITabBarItem(tabBarSystemItem: .downloads, tag: 1)

        return UINavigationController(rootViewController: fugaVC)

    }

    func createTabbar() -> UITabBarController {
        let tabbar = UITabBarController()
        UITabBar.appearance().tintColor = .systemGreen
        tabbar.viewControllers = [createHogeNC(), createFugaNC()]

        return tabbar
    }


    func configureNavigationBar() {
        UINavigationBar.appearance().tintColor = .systemGreen
    }

それぞれのタブが、ナビゲーションコントローラを持ち、そのナビゲーションコントローラのは、それぞれビューコントローラーをもつので、
タブバーを window.rootViewController に指定しています。

これで完成です。

デバッグビューヒエラルキー

デバックビューヒエラルキーで
わかりやすくタブ、ナビゲーション、ビューコントローラーの構造を確認できます。

スクリーンショット 2024-05-15 1.35.07.png

参考

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0