Tong's Blog

[iOS] UINavigationController 에 대해 본문

iOS/Swift

[iOS] UINavigationController 에 대해

통스 2021. 8. 31. 19:33
반응형

안녕하세요.

이래저래 많은 일들이 있어서 그동안 포스트를 소홀히 했는데, 이제 다시 꾸준히 해보려고 합니다.

 

오늘은 UINavigationController 에 대해 알아보려고 합니다.

UINavigationController 는 제가 처음에 iOS 에 대해 잘 모를 때, UIViewController 와의 관계에 대해서 많이 헷갈렸던 부분인데요. 그때의 기억을 되살려 이번 포스트를 작성해보겠습니다.

 

마찬가지로 애플공식문서부터 살펴보겠습니다.

https://developer.apple.com/documentation/uikit/uinavigationcontroller

 

Apple Developer Documentation

 

developer.apple.com

다른 컴포넌트에 비해서 내용이 많이 있는데 첫번째 단락만 우선 살펴보겠습니다.

 

A container view controller that defines a stack-based scheme for navigating hierarchical content.

Overview
A navigation controller is a container view controller that manages one or more child view controllers in a navigation interface. In this type of interface, only one child view controller is visible at a time. Selecting an item in the view controller pushes a new view controller onscreen using an animation, thereby hiding the previous view controller. Tapping the back button in the navigation bar at the top of the interface removes the top view controller, thereby revealing the view controller underneath.

의역하자면 Stack 기반의 container view controller 이고, 제공하는 navigation 인터페이스로 1개 이상의 view controller 를 관리할 수 있다고 합니다. Stack 기반이므로 최상단에 있는 하나의 view controller 만이 보여지게 되고 view controller 를 push 혹은 pop 을 통해 보여질 view controller 를 결정하게 된다고 합니다.

 

전체적인 개념에 대해서는 잘 정리된 거 같은데 개인적으로 처음에 사용하면서 공부할 때는 많이 헷갈렸던 것 같습니다.

우선, UINavigationController 가 가지고 있는 요소들은 아래와 같습니다.

 

1. viewControllers: navigation controller 는 여러개의 view controller 를 관리할 수 있는 container view controller 이기 때문에 해당 navigation stack 에 쌓인 view controller 들을 배열 형태로 가지고 있습니다. 해당 배열은 push, pop 형태로 관리됩니다.

 

2. navigationBar: 앱을 사용하다 보면 상단에 타이틀, 뒤로가기, 설정등 특정 영역에 UI 요소들이 배치된 경우를 볼 수 있는데, 해당 영역을 navigationBar라고 합니다. 해당 navigationBar 를 통해 굳이 UI를 추가하거나 세팅할 필요없이 해당 view controller 를 위한 UI를 설정할 수 있습니다.

 

3. toolbar: 사파리 앱에서 흔히 아래쪽에 공유하기나 여러 버튼들이 모여있는 것을 볼 수 있는데, 이를 toolbar라고 합니다. 기본적으로 navigation controller 에서는 숨김처리 되어 있지만, 숨김을 해제하고 해당 영역을 설정할 수 있습니다.

 

4. delegate: UITableViewDelegate 처럼 UINavigationController 에도 특정 Event에서 사용할 수 있는 delegate가 선언되어 있습니다. 보통 특정 view controller가 보여지거나, 이동간 애니메이션을 설정하기 위해 사용합니다.

 

이번에는 기본적인 UINavigationController 사용법에 대해서 알아보겠습니다.

우리가 일반적인 UIViewController 를 선언하고 사용하는 방법은 아래와 같습니다.

import UIKit

class RootViewController: UIViewController {
    ...
    
    func showFirstViewController() {
    	// 선언
        let firstVC = UIViewController()
        
        // 화면 띄우기
        self.present(firstVC, animated: true)
    }
    
    ...
}

하지만 이번에 사용하는 것은 UINavigationController 이므로 다르게 사용해야 합니다. navigation controller 는 선언시 기본이 될 root view controller 를 지정해야합니다.

import UIKit

class RootViewController: UIViewController {
    ...
    
    func showNavigationController() {
    	// 선언
        let firstVC = UIViewController()
        let naviC = UINavigationController(rootViewController: firstVC)
        
        // 화면 띄우기
        self.present(naviC, animated: true)
    }
    
    ...
}

이번에는 화면전환에 대한 두 view controller에 대한 차이를 보겠습니다.

우선 각각의 차이를 보기 위한 뷰를 구성해봤습니다.

각 버튼 액션에는 UIViewController 에서의 화면전환방법과, UINavigationController를 활용한 화면 전환을 하는 함수를 설정했습니다

class FirstViewController: UIViewController {
    let presentButton = UIButton()
    let pushButton = UIButton()
    
    ...
    
    @objc func showPresent() {
        let secondVC = SecondViewController()
        self.present(secondVC, animated: true)
    }
    
    @objc func showPush() {
        let secondVC = SecondViewController()
        self.navigationController?.pushViewController(secondVC, animated: true)
    }
}

각각을 실행한 경우의 차이는 다음과 같습니다.

왼: UIViewController present / 오른쪽: UINavigationController pushViewController

단순히 새로운 view controller 를 띄우는 present 와 달리 pushViewController 는 navigation controller 에 관리되는 view controller 를 추가해주고 최상단으로 띄워줄 뿐만 아니라 navigation bar 를 추가해줌으로서 최상단에 보여줄 view controller 에 필요한 UI를 쉽게 추가해줄 수 있습니다.

 

반대로 현재 보여지고 있는 view controller 를 제거하는 방식도 간단히 보겠습니다.

class SecondViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.backgroundColor = .green
    }
    
    // View Controller
    func dismissViewController() {
        self.dismiss(animated: true)
    }
    
    // Navigation Controller
    func popViewController() {
        self.navigationController?.popViewController(animated: true)
    }
}

 

그러면 이러한 navigation controller 는 언제 사용하는게 좋을까요?

사실 이 부분은 주관적인 부분이 많이 개입되는 부분이지만 단계적, 순차적으로 view controller 를 띄워주고 띄워진 view controller 들을 관리하고 싶을 때 사용하면 좋을 것이라고 생각합니다.

 

오늘은 UINavigationController 에 대한 간단한 설명과 사용법에 대해 알아봤습니다.

부족한 글 읽어주셔서 감사하고 피드백은 언제나 환영합니다.

반응형

'iOS > Swift' 카테고리의 다른 글

[SwiftUI] task 와 onAppear 차이  (0) 2024.03.12
[Swift] 이메일(e-mail) 유효성 체크하는 정규식 만들기  (0) 2022.10.14
[Swift] ReactorKit Framework  (0) 2021.05.24
[Swift] Delegate란?  (0) 2021.02.16
[Swift] Foundation 간단 정리  (0) 2020.12.23
Comments