UIViewController 개념
UIKit 앱의 뷰 계층을 관리하는 개체입니다.
UIViewController
를 가짐.UIViewController
내부에 UIView
, UIButton
, UIScrollView
등 UIKit 의 UI 클래스들을 배치하며 화면을 구성한다.ViewController 생명주기
App Lifecycle
) → [1-3. Xcode 빌드] 강의에서 공부했음.ViewController Lifecycle
)ViewController Lifecycle 메서드 호출 확인
▪️ ViewController 에서 버튼을 클릭하면 AdamViewController 로 이동하도록 구현합니다.
//
// SceneDelegate.swift
//
import UIKit
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
guard let windowScene = scene as? UIWindowScene else { return }
let window = UIWindow(windowScene: windowScene)
window.rootViewController = UINavigationController(rootViewController: ViewController())
window.makeKeyAndVisible()
self.window = window
}
// ...
}
NSLayoutConstraint 로 구현
//
// ViewController.swift
//
import UIKit
class ViewController: UIViewController {
let button = UIButton()
override func viewDidLoad() {
super.viewDidLoad()
configureUI()
print("viewDidLoad")
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
print("viewWillAppear")
}
override func viewIsAppearing(_ animated: Bool) {
super.viewIsAppearing(animated)
print("viewIsAppearing")
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
print("viewDidAppear")
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
print("viewWillDisappear")
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
print("viewDidDisappear")
}
private func configureUI() {
view.addSubview(button)
view.backgroundColor = .white
button.setTitle("페이지 이동", for: .normal)
button.addTarget(self, action: #selector(buttonTapped), for: .touchDown)
button.backgroundColor = .red
button.setTitleColor(.white, for: .normal)
button.titleLabel?.font = .boldSystemFont(ofSize: 30)
button.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
button.widthAnchor.constraint(equalToConstant: 200),
button.heightAnchor.constraint(equalToConstant: 120),
button.centerXAnchor.constraint(equalTo: view.centerXAnchor),
button.centerYAnchor.constraint(equalTo: view.centerYAnchor)
])
}
@objc
private func buttonTapped() {
self.navigationController?.pushViewController(AdamViewController(), animated: true)
}
}
//
// AdamViewController.swift
//
//
import UIKit
class AdamViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .orange
print("AdamViewController viewDidLoad")
}
}
override func viewWillAppear(_ animated: Bool) {
print("viewWillAppear")
self.view.backgroundColor = UIColor(
red: .random(in: 0...1),
green: .random(in: 0...1),
blue: .random(in: 0...1),
alpha: 1.0
)
self.button.backgroundColor = UIColor(
red: .random(in: 0...1),
green: .random(in: 0...1),
blue: .random(in: 0...1),
alpha: 1.0
)
}
동그라미네모세모 실종 사건