티스토리 뷰
😱내가 하고 싶었던 건,,,정말 간단했다구,,,
그냥 버튼을 누르면 네비게이션 컨트롤러로 연결되었으면 좋겠다ㅏㅏㅏ (코드로)
그게 다였는데,,,토요일 일요일을 다 써도 그게 되지 않았다.🤬
혼자라도 보기 위해 여기에 정리를 해보는걸로 🤗
1. 스토리보드를 이용한 연결
프로젝트의 메인스토리보드에서 뷰컨트롤러를 선택하고, [Editor]-[Embed In]-[Navigation Controller]

그러면 아래처럼 좌측에 네비게이션 컨트롤러가 쨘! 하고 생기쥬.

그리고 나서 아래와 같은 코드를 viewController.swift에서 쳐주면,
//
// ViewController.swift
// Navigation(storyboard)
//
// Created by 순진이 on 2021/11/28.
//
import UIKit
class ViewController: UIViewController {
let btn = UIButton()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .brown
btn.setTitle("TEST", for: .normal)
let viewWidth = view.frame.size.width
let viewHeight = view.frame.size.height
btn.frame = CGRect(x: viewWidth/3, y: viewHeight/3, width: 200, height: 200)
btn.backgroundColor = .green
view.addSubview(btn)
btn.addTarget(self, action: #selector(btnTapped(_:)), for: .touchUpInside)
}
@objc func btnTapped (_ sender: UIButton) {
navigationController?.pushViewController(SecondViewController(), animated: true)
}
}
class SecondViewController: UIViewController {
// MARK: -Life Cycles
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .red
}
}

2. 스토리보드를 삭제한 후 코드로만 구현
우선 Indicator에서 아래 두 작업을 해주도록 합니다.
-Main Interface에 써있던 Main을 삭제

-Info.plist에서 스토리보드 내역 삭제

-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
window?.makeKeyAndVisible()
let vc = ViewController()
let navController = UINavigationController(rootViewController: vc)
window?.rootViewController = navController
}
-viewController.swift
//
// ViewController.swift
// NavigationTest3
//
// Created by 순진이 on 2021/11/28.
//
import UIKit
class ViewController: UIViewController {
let button = UIButton()
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = .yellow
self.navigationItem.title = "First ViewContorller"
setBasics()
setLayout()
}
}
//MARK: -UI
extension ViewController {
final private func setBasics() {
button.setTitle("push", for: .normal)
button.backgroundColor = .magenta
view.addSubview(button)
button.addTarget(self, action: #selector(btnTapped(_:)), for: .touchUpInside)
}
final private func setLayout() {
button.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
button.centerXAnchor.constraint(equalTo: view.safeAreaLayoutGuide.centerXAnchor),
button.centerYAnchor.constraint(equalTo: view.safeAreaLayoutGuide.centerYAnchor)
])
}
@objc func btnTapped (_ sender: UIButton) {
navigationController?.pushViewController(SecondViewController(), animated: true)
}
}
class SecondViewController: UIViewController {
// MARK: -Life Cycles
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .magenta
self.navigationItem.title = "Seond View"
}
}

3. 실패 : 스토리보드 삭제 안한 후 코드 구현
스토리보드로 임베드 하지도 않고, 스토리보드 삭제도 하지 않은 상태에서 버튼만 누르면 다른 뷰컨트롤러로 넘어가도록 하려고 했으나, 계속 구현이 되지 않음
import UIKit
class ViewController: UIViewController {
let button = UIButton()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .systemBlue
setLayout()
}
func setLayout() {
button.setTitle("Next to", for: .normal)
button.setTitleColor(.black, for: .normal)
button.backgroundColor = .yellow
button.frame = CGRect(x: 100, y: 100, width: 200, height: 50)
view.addSubview(button)
button.addTarget(self, action: #selector(btnTapped(_:)), for: .touchUpInside)
}
@objc func btnTapped(_ sender: UIButton) {
let rootVC = SecondViewController()
let navVC = UINavigationController(rootViewController: rootVC)
self.navigationController?.pushViewController(navVC, animated: true)
}
}
class SecondViewController: UIViewController {
// MARK: -Life Cycles
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .yellow
self.navigationItem.title = "제발 나와라"
}
}
선생님께 물어보니, push하려는 뷰컨(navVC)에도 navigation컨트롤러가 깔려(?) 있어야 한다고!!
navVC에서 nav가 깔려있지 않기 때문에 navigationController?가 옵셔널 체이닝 실패 -> push 작업이 실행되지 않음
네비게이션 컨트롤러 잘하고 싶다,,,
'순진이의 하루' 카테고리의 다른 글
친구들과 노션으로 미션하기 (0) | 2022.01.24 |
---|---|
[swift] 11/21(일) TabBarController 만들어보기 (0) | 2021.11.22 |
11/17(수) 2번째 스터디 (0) | 2021.11.18 |
11/14(일) 마음대로 되는 것이 하나 없다. (0) | 2021.11.15 |
11.12(금) tistory의 어려움 (0) | 2021.11.12 |
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크