티스토리 뷰

지난 번에는 스토리보드에서 탭바컨트롤러를 만들어봤는데요.

스토리보드가 없어도 탭바컨트롤러를 만들 수 있다네여?! 롸?!

 

그래서 오늘은 스토리보드 없이 UITabBarController 구현하기 입니다.

 


1. Main연결 삭제하기

프로젝트를 만든 후 제일 먼저 나오는 General 셋팅에 보면 Development Info-Main Interface가 있는데요.

여기에 있는 Main을 삭제해주시면 됩니다.

 

 

2. Info.plist에서 스토리보드 항목 삭제 & 스토리보드 삭제

dicator에 있는 Info.plist에서 Storyboard Name 항목도 삭제해주고, 이제 필요없어진 Main.storyboard항목도 Bye~

그리고 탭바를 두개 만들 예정이니까, 연결할 뷰컨트롤러(ViewController)를 두개 만들어줍니다요.

저는 FirstViewController, SecondViewController로 만들었쥬.

 

아! 그리고 각 뷰컨을 구별할 수 있도록 FirstViewController, SecondViewController의 배경색을 설정해주었어요.

//  FirstViewController.swift

import UIKit

class FirstViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .green
    }
}
//  SecondViewController.swift

import UIKit

class SecondViewController: UIViewController {

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

이제 sceneDelegate.swift에서 작업을 해주면 됩니다.

sceneDelegate.swift에 가시면 아래와 같은 메서드가 있어요. 여기서 작업을 해야하쥬.

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

 

 

만약 UITabBarController를 만들 게 아니라면 간단하게 아래처럼 작업해주면, ViewController가 루트뷰가 되는 프로젝트를 만들 수 있답니다.

// sceneDelegate.swift
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { 
        guard let scene = (scene as? UIWindowScene) else { return }
        window = UIWindow(frame: scene.coordinateSpace.bounds)
        window?.windowScene = scene
        let vc = ViewController()
        window?.rootViewController = vc
        window?.makeKeyAndVisible()
}

 

 

그렇지만, 우리는 오늘 탭바컨트롤러를 만들 예정이므로, 아래와 같이 작업을 해줍니다. 

이제 여기서부터 각 탭의 설정을 해줄게요.

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

        guard let scene = (scene as? UIWindowScene) else { return }
        window = UIWindow(frame: scene.coordinateSpace.bounds)
        window?.windowScene = scene
        let tabBarVC = UITabBarController()        
        window?.rootViewController = tabBarVC
        window?.makeKeyAndVisible()
    }

 

 

TabBarController의 경우, 각 탭별로 연결된 뷰가 있어야겠쥬?

그냥 뷰컨트롤러를 연결해도 되지만, 저는 각 탭을 NavigationController로 만들어주어 스택 형태로 쌓이게 만들어줄게요!

그리고 viewContorllers 메서드를 통해 우리가 만든 네비게이션컨트롤러를 탭바의 각 탭으로 만들어줍니다.

//탭바컨트롤러의 객체 찍어내기
let tabBarVC = UITabBarController()
        
//각 탭과 연결될 네비게이션컨트롤러 설정
let fisrtVC = FirstViewController()
let secondVC = SecondViewController()
        
let nav1 = UINavigationController(rootViewController: fisrtVC)
let nav2 = UINavigationController(rootViewController: secondVC)

tabBarVC.viewControllers = [nav1, nav2]
//tabBarVC.setViewControllers([nav1, nav2], animated: true)

 

setViewControllers라는 메서드도 viewControllers 메서드와 같은 역할을 하기 때문에, 주석 처리를 한 코드를 적어도 같은 결과가 나와욧!

 

 

 

근데 탭바 아이템이나 타이틀이 없으니까, 너무 이상하져?

그래서 간단한 탭바 아이템을 넣어보도록 하겠어여.

 

먼저 탭바의 타이틀부터 설정해볼거에여.

 

 

 

UINavigationController는 navigationBar라는 속성을 갖는데요, navigationBar 속성은 UINavigationBar타입이에요.

UINavigationBar는 topItem이라는 속성을 가지구 있구요. (UINavigationItem 타입)

이 topItem 속성은 UINavigationItem타입이기 때문에 UINavigationItem이 가진 title이라는 속성을 갖쥬.

 

 

 

그래서 아래처럼 설정해줄 수 있는거에요.

nav1.navigationBar.topItem?.title = "First VC"
nav2.navigationBar.topItem?.title = "Second VC"

 

 

그 다음은 TabBarItem 차례!

UITabBarItem 클래스에는 많은 생성자가 있는데요,

간단한 예제이므로 init(title:image:tag:) 생성자를 사용할게유.

 

//첫번째 탭바아이콘 설정
nav1.tabBarItem = UITabBarItem(title: "First", image: UIImage(systemName: "pencil"), tag: 0)
        
//두번째 탭바아이콘 설정        
nav2.tabBarItem = UITabBarItem(title: "Second", image: UIImage(systemName: "folder"), tag: 1)

tabBarVC.viewControllers = [nav1, nav2]
//tabBarVC.setViewControllers([nav1, nav2], animated: true)

 

마지막으로 우리가 설정한 탭바컨트롤러를 윈도우의 루트뷰 컨트롤러로 바꿔주면 됩니당!!

+ 그리고 우리가 설정한 뷰를 윈도우에 보여주는 메서드 makeKeyAndVisible()까지 설정하면 끝!

 

window?.rootViewController = tabBarVC
window?.makeKeyAndVisible()

 

 

이제 모든 게 다 설정되었어요!

전체코드를 한 번 볼게욧!

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

        guard let scene = (scene as? UIWindowScene) else { return }
        window = UIWindow(frame: scene.coordinateSpace.bounds)
        window?.windowScene = scene
        
        let tabBarVC = UITabBarController()
        
        let fisrtVC = FirstViewController()
        let secondVC = SecondViewController()
        
        let nav1 = UINavigationController(rootViewController: fisrtVC)
        let nav2 = UINavigationController(rootViewController: secondVC)
        
        //뷰컨 타이틀 설정
        nav1.navigationBar.topItem?.title = "First VC"
        nav2.navigationBar.topItem?.title = "Second VC"
        
        //탭바아이템 설정
        nav2.tabBarItem = UITabBarItem(title: "Second", image: UIImage(systemName: "folder"), tag: 1)
        nav1.tabBarItem = UITabBarItem(title: "First", image: UIImage(systemName: "pencil"), tag: 0)
        
        
        //tabBarVC.viewControllers = [nav1, nav2]
        tabBarVC.setViewControllers([nav1, nav2], animated: true)
        
        window?.rootViewController = tabBarVC
        window?.makeKeyAndVisible()

        
        
    }

 

혹시 틀린 게 있으면 언제든지 알려주십셔 슨배님덜!!

 

참고 : 

https://icksw.tistory.com/48?category=877391 

 

[iOS 앱개발 프로그래밍] 스토리보드 없이 네비게이션 컨트롤러 만들기

모든 것을 스토리보드 없이 코드로 만들어보려고 노력 중인데요, 그래서 이번 글에서는 스토리보드 없이 네비게이션 컨트롤러를 만들어 보려고 합니다. 우선 스토리보드를 삭제하는 작업과 셋

icksw.tistory.com

 

공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크