UIKit
코드베이스로 UINavigationController 구현하기
by 리버🐦🔥
2023. 10. 15.
|
<UINavigationController>
- 네비게이션 스택을 관리하고 화면 간에 이동하는 데 사용
- 이전 화면으로 이동하거나 새로운 화면으로 이동하는 데 사용
- 기본적으로 스택 구조로 뷰를 쌓아가며 이동
[Method & Property]
- pushViewController(): 목적지 뷰로 이동하면서 스택에 쌓는 함수
등… 프로퍼티 및 메서드 추가로 공부해보기! |
import UIKit
class UINavigationControllerTest: UIViewController {
private lazy var uiNavigationController: UINavigationController = {
let rootViewController = UIViewController()
rootViewController.view.backgroundColor = .white
rootViewController.title = "Root View"
let navigationController = UINavigationController(rootViewController: rootViewController)
navigationController.view.translatesAutoresizingMaskIntoConstraints = false
return navigationController
}()
private lazy var nextButton: UIButton = {
let button = UIButton()
button.setTitle("Next", for: .normal)
button.setTitleColor(.blue, for: .normal)
button.addTarget(self, action: #selector(nextButtonTapped), for: .touchUpInside)
button.translatesAutoresizingMaskIntoConstraints = false
return button
}()
@objc private func nextButtonTapped() {
let destinationViewController = NextViewControllerTest()
navigationController?.pushViewController(destinationViewController, animated: true)
}
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = .systemGray
self.view.addSubview(uiNavigationController.view)
addChild(uiNavigationController)
uiNavigationController.didMove(toParent: self)
view.addSubview(nextButton)
setLayout()
}
private func setUINavigaionControllerLayout() {
let uiNavigationControllerConstraint = [
uiNavigationController.view.topAnchor.constraint(equalTo: view.topAnchor),
uiNavigationController.view.leadingAnchor.constraint(equalTo: view.leadingAnchor),
uiNavigationController.view.trailingAnchor.constraint(equalTo: view.trailingAnchor),
uiNavigationController.view.bottomAnchor.constraint(equalTo: view.bottomAnchor)
]
NSLayoutConstraint.activate(uiNavigationControllerConstraint)
}
private func setNextButtonLayout() {
let nextButtonConstraint = [
nextButton.centerXAnchor.constraint(equalTo: view.centerXAnchor),
nextButton.centerYAnchor.constraint(equalTo: view.centerYAnchor)
]
NSLayoutConstraint.activate(nextButtonConstraint)
}
private func setLayout() {
setUINavigaionControllerLayout()
setNextButtonLayout()
}
}
class NextViewControllerTest: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .gray
title = "Next View"
}
}
import SwiftUI
@available(iOS 13.0.0, *)
struct UINavigationControllerTestPreview: PreviewProvider {
static var previews: some View {
UINavigationControllerTest().toPreview()
}
}