iOS TabBarController without storyboard

Joseph Kim·2022년 3월 10일
1

iOS

목록 보기
4/4

시작하며

TabBarContoller를 스토리보드 없이 만드는 예제를 정리한다. '개발하는 정대리' 유튜브를 보며 공부한 것을 정리해 놓았다.
개발하는정대리 유튜브

초기세팅

지난번 포스팅한 'iOS 앱 스토리보드 없이 개발 세팅'을 참고하여 초기세팅을 해 놓으면 된다.

먼저 MainTabBarController를 만들기 위해서 파일을 하나 추가한다. 강의에서는 일반 swift파일을 추가하는데, Cocoa Touch Class로 하고 subclass로 UITabBarController를 설정하면 더 편하다. 그리고 MainTabBarController의 인스턴스를 만들고 rootView를 만든 인스턴스로 설정한다.

let mainTC = MainTabBarController()
window?.rootViewController = mainTC

TabBarController 세팅

TabBarController안에 NavigationController를 만들기 위해서 ViewController를 먼저 수정한다. 상속할 때, 타이틀과 색등을 받아서 ViewController에 아래와 같이 추가 한다.

 convenience init(title: String, bgColor: UIColor) {
        self.init()
        self.title = title
        self.view.backgroundColor = bgColor
    }

ViewController의 전체 코드는 아래와 같다.

import UIKit

class MyViewController: UIViewController {

    convenience init(title: String, bgColor: UIColor) {
        self.init()
        self.title = title
        self.view.backgroundColor = bgColor
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }

}

MainTabBarControler에서 네비게이션컨트롤러를 설정한다.

let firstNC = UINavigationController.init(rootViewController: MyViewController(title: "첫번째", bgColor: UIColor.orange))
let secondNC = UINavigationController.init(rootViewController: MyViewController(title: "두번째", bgColor: UIColor.green))
let thirdNC = UINavigationController.init(rootViewController: MyViewController(title: "세번째", bgColor: UIColor.blue))
let fourthNC = UINavigationController.init(rootViewController: MyViewController(title: "네번째", bgColor: UIColor.gray))
let fifthNC = UINavigationController.init(rootViewController: MyViewController(title: "다섯번째", bgColor: UIColor.yellow))

UITabBarController의 viewControllers Array를 만들어 준다.

self.viewControllers = [firstNC,secondNC,thirdNC,fourthNC,fifthNC]

네비게이션아이템을 설정한다.

let firstTabBarItem = UITabBarItem(title: "첫번째", image: UIImage(systemName: "mic"), tag: 0)
let secondTabBarItem = UITabBarItem(title: "두번째", image: UIImage(systemName: "sun.min"), tag: 1)
let thirtdTabBarItem = UITabBarItem(title: "세번째", image: UIImage(systemName: "moon"), tag: 2)
let fourthTabBarItem = UITabBarItem(title: "네번째", image: UIImage(systemName: "pencil"), tag: 3)
let fifthTabBarItem = UITabBarItem(title: "다섯번째", image: UIImage(systemName: "keyboard"), tag: 4)

각 네비게이션의 tabBaritem을 위에 아이템으로 설정한다.

firstNC.tabBarItem = firstTabBarItem
secondNC.tabBarItem = secondTabBarItem
thirdNC.tabBarItem = thirtdTabBarItem
fourthNC.tabBarItem = fourthTabBarItem
fifthNC.tabBarItem = fifthTabBarItem코드를 입력하세요

이상태로 빌드를 하게 되면 유튜브와 다르게 아래 탭부분에 칼라도 모두 동일해서 아이콘을 구별하기 힘들다. 따라서 아래와 같이 탭부분의 칼라를 설정한다.

self.tabBar.backgroundColor = UIColor.white

아래와 같은 화면을 볼 수 있다.

전체코드

1. SceneDelegate.swift

import UIKit

class SceneDelegate: UIResponder, UIWindowSceneDelegate {

    var window: UIWindow?


    func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
        // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
        // If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
        // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
//        guard let _ = (scene as? UIWindowScene) else { return }
        guard let windowScene = (scene as? UIWindowScene) else {return}
        window = UIWindow(frame: UIScreen.main.bounds)
//        let vc = ViewController()
//        let navVC = UINavigationController(rootViewController: vc)
        let mainTC = MainTabBarController()
        window?.rootViewController = mainTC
        window?.makeKeyAndVisible()
        window?.windowScene = windowScene
    }

    func sceneDidDisconnect(_ scene: UIScene) {
        // Called as the scene is being released by the system.
        // This occurs shortly after the scene enters the background, or when its session is discarded.
        // Release any resources associated with this scene that can be re-created the next time the scene connects.
        // The scene may re-connect later, as its session was not necessarily discarded (see `application:didDiscardSceneSessions` instead).
    }

    func sceneDidBecomeActive(_ scene: UIScene) {
        // Called when the scene has moved from an inactive state to an active state.
        // Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive.
    }

    func sceneWillResignActive(_ scene: UIScene) {
        // Called when the scene will move from an active state to an inactive state.
        // This may occur due to temporary interruptions (ex. an incoming phone call).
    }

    func sceneWillEnterForeground(_ scene: UIScene) {
        // Called as the scene transitions from the background to the foreground.
        // Use this method to undo the changes made on entering the background.
    }

    func sceneDidEnterBackground(_ scene: UIScene) {
        // Called as the scene transitions from the foreground to the background.
        // Use this method to save data, release shared resources, and store enough scene-specific state information
        // to restore the scene back to its current state.
    }


}

2. MyViewController.swift

import UIKit

class MyViewController: UIViewController {

    convenience init(title: String, bgColor: UIColor) {
        self.init()
        self.title = title
        self.view.backgroundColor = bgColor
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }

}

3. MainTabBarController.swift

import UIKit

class MainTabBarController: UITabBarController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.tabBar.backgroundColor = UIColor.white
        
        let firstNC = UINavigationController.init(rootViewController: MyViewController(title: "첫번째", bgColor: UIColor.orange))
        let secondNC = UINavigationController.init(rootViewController: MyViewController(title: "두번째", bgColor: UIColor.green))
        let thirdNC = UINavigationController.init(rootViewController: MyViewController(title: "세번째", bgColor: UIColor.blue))
        let fourthNC = UINavigationController.init(rootViewController: MyViewController(title: "네번째", bgColor: UIColor.gray))
        let fifthNC = UINavigationController.init(rootViewController: MyViewController(title: "다섯번째", bgColor: UIColor.yellow))

        self.viewControllers = [firstNC,secondNC,thirdNC,fourthNC,fifthNC]
        
        let firstTabBarItem = UITabBarItem(title: "첫번째", image: UIImage(systemName: "mic"), tag: 0)
        let secondTabBarItem = UITabBarItem(title: "두번째", image: UIImage(systemName: "sun.min"), tag: 1)
        let thirtdTabBarItem = UITabBarItem(title: "세번째", image: UIImage(systemName: "moon"), tag: 2)
        let fourthTabBarItem = UITabBarItem(title: "네번째", image: UIImage(systemName: "pencil"), tag: 3)
        let fifthTabBarItem = UITabBarItem(title: "다섯번째", image: UIImage(systemName: "keyboard"), tag: 4)
        
        firstNC.tabBarItem = firstTabBarItem
        secondNC.tabBarItem = secondTabBarItem
        thirdNC.tabBarItem = thirtdTabBarItem
        fourthNC.tabBarItem = fourthTabBarItem
        fifthNC.tabBarItem = fifthTabBarItem
        // Do any additional setup after loading the view.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */

}
profile
I'm working on GM TCK(old, GM Korea). I'm just starting Mobile App Development. Previously I've worked at various Vehicle Development Area

0개의 댓글