이 글에서 UIViewController로 원하는 화면을 만들고 앱의 첫 화면으로 연결하는 방법을 알아보겠습니다.
먼저 코드로 UI를 구성하는 방법을 아래 링크에서 보고 오시는 것을 추천 드립니다.
1. UIViewController을 상속받아 화면 클래스를 만듭니다.
아래와 같이 화면을 구성합니다.
import UIKit
class FlashlightViewController: UIViewController {
private let imageView1 = UIImageView()
private let imageView2 = UIImageView()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
attribute()
layout()
}
private func attribute() {
self.view.backgroundColor = .systemMint
imageView1.image = UIImage(named: "torch_off")
imageView1.contentMode = .scaleAspectFit
imageView2.image = UIImage(named: "power_off")
imageView2.contentMode = .scaleAspectFit
}
private func layout() {
let spacing: CGFloat = 100
self.view.addSubview(imageView1)
// Enable Auto Layout for the image view
imageView1.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
imageView1.centerXAnchor.constraint(equalTo: view.centerXAnchor),
imageView1.topAnchor.constraint(equalTo: view.topAnchor, constant: 200),
imageView1.widthAnchor.constraint(equalToConstant: 100),
imageView1.heightAnchor.constraint(equalToConstant: 100)
])
self.view.addSubview(imageView2)
// Enable Auto Layout for the second image view
imageView2.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
imageView2.centerXAnchor.constraint(equalTo: view.centerXAnchor),
imageView2.topAnchor.constraint(equalTo: imageView1.bottomAnchor, constant: spacing),
imageView2.widthAnchor.constraint(equalToConstant: 200),
imageView2.heightAnchor.constraint(equalToConstant: 200)
])
}
}
2. SeneDelegate에서 새로 만든 화면 클래스를 연결해 줍니다.
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
// Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
// If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
// This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
guard let windowScene = (scene as? UIWindowScene) else { return }
window = UIWindow(windowScene: windowScene)
window?.rootViewController = FlashlightViewController()
window?.makeKeyAndVisible()
}
3. 시뮬레이터에서 확인합니다.