저는 UIKit으로 iOS 모바일 앱을 개발할 때 늘 코드로 UI를 만드는 방식을 선호해 왔습니다. 스토리보드는 처음에는 편리해 보일 수 있지만, 저를 프로그래머라기보다 디자이너처럼 느끼게 만드는 경향이 있습니다. 게다가 확장성과 관리 용이성 면에서 저는 항상 코드 방식이 더 낫다고 느낍니다.
이 글에서는 UIKit으로 탭 바 컨트롤러와 내비게이션 컨트롤러를 함께 만드는 과정을 자세히 설명하겠습니다.
SceneDelegate 설정하기
코드 방식을 도입하는 첫 단계는 앱의 루트 코드를 수정하는 것입니다. 저는 이것을 "루트"라고 부르는데, React/React Native의 App.js나 index.js가 떠오릅니다. 이것이 앱 또는 씬의 진입점 역할을 합니다. iOS에서는 SceneDelegate 클래스 안에 scene 함수가 있으며, 앱을 코드 방식으로 개발하도록 구성하는 데는 이 함수만 사용하겠습니다.
아래는 SceneDelegate 클래스의 기본 구조입니다.
import UIKit
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
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 _ = (scene as? UIWindowScene) else { return }
}
func sceneDidDisconnect(_ scene: UIScene) {
// Called as the scene is being released by the system.
// This occurs shortly after the scene enters the background, or when its session is discarded.
// Release any resources associated with this scene that can be re-created the next time the scene connects.
// The scene may re-connect later, as its session was not necessarily discarded (see `application:didDiscardSceneSessions` instead).
}
func sceneDidBecomeActive(_ scene: UIScene) {
// Called when the scene has moved from an inactive state to an active state.
// Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive.
}
func sceneWillResignActive(_ scene: UIScene) {
// Called when the scene will move from an active state to an inactive state.
// This may occur due to temporary interruptions (ex. an incoming phone call).
}
func sceneWillEnterForeground(_ scene: UIScene) {
// Called as the scene transitions from the background to the foreground.
// Use this method to undo the changes made on entering the background.
}
func sceneDidEnterBackground(_ scene: UIScene) {
// Called as the scene transitions from the foreground to the background.
// Use this method to save data, release shared resources, and store enough scene-specific state information
// to restore the scene back to its current state.
}
}
여기서 수정할 것은 아래 함수뿐입니다.
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 _ = (scene as? UIWindowScene) else { return }
}
SceneDelegate의 scene 함수 수정하기
아래 코드에서는 guard 문으로 windowScene을 안전하게 가져옵니다. 이어서 이 windowScene을 SceneDelegate 클래스에 정의된 window 프로퍼티에 할당합니다. 마지막으로 makeKeyAndVisible 메서드를 호출해 이 window를 key window로 만듭니다.
var window: UIWindow?
func scene(\_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
guard let windowScene = (scene as? UIWindowScene) else { return }
window?.windowScene = windowScene
window?.makeKeyAndVisible()
}
다음으로 탭 바 컨트롤러를 만드는 데 집중해 봅시다. 이 컨트롤러는 앱의 각 탭에 해당하는 뷰 컨트롤러들을 관리합니다. 예를 들어 탭이 두 개라면 별도의 내비게이션 컨트롤러가 두 개 필요합니다. 그런데 왜 내비게이션 컨트롤러를 쓸까요? 각 탭 안에 자체 내비게이션 컨트롤러를 두고 싶기 때문입니다. "Profile" 탭을 예로 들어 보겠습니다. 프로필 화면이 그 탭의 메인 뷰가 되겠지만, 탭 안에서 이동하고 싶은 다른 뷰가 더 있을 수 있습니다. 그래서 각 탭 항목마다 내비게이션 컨트롤러를 씁니다. 내비게이션 컨트롤러는 탭 안의 여러 뷰 컨트롤러 사이를 매끄럽게 이동하는 데 필요한 기능을 제공합니다.
코드로 옮겨 봅시다!
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
guard let windowScene = (scene as? UIWindowScene) else { return }
window?.windowScene = windowScene
window?.makeKeyAndVisible()
let tabbar = UITabBarController()
let firstVC = UINavigationController(rootViewController: ViewController())
let secondVC = UINavigationController(rootViewController: SecondViewController())
firstVC.tabBarItem = UITabBarItem(title: "Home", image: UIImage(systemName: "house"),selectedImage: UIImage(systemName: "house.fill"))
secondVC.tabBarItem = UITabBarItem(title: "Profile", image: UIImage(systemName: "person"),selectedImage: UIImage(systemName: "person.fill"))
tabbar.viewControllers = [firstVC, secondVC]
window?.rootViewController = tabbar
}
탭 바 컨트롤러를 초기화한 뒤, 앱의 두 탭 항목에 해당하는 내비게이션 컨트롤러 두 개를 만듭니다. 첫 번째 뷰 컨트롤러는 기본 뷰 컨트롤러이고, 두 번째 뷰 컨트롤러인 SecondViewController는 다음 섹션에서 다룹니다. SecondViewController는 기본 뷰 컨트롤러와 비슷한 평범한 뷰 컨트롤러입니다.
탭 항목을 구성하기 위해 각 내비게이션 컨트롤러의 tabItem 프로퍼티를 UITabBarItem으로 설정합니다.
마지막으로 만들어 둔 뷰 컨트롤러들을 탭 바 컨트롤러의 viewControllers 프로퍼티에 할당합니다.
그리고 가장 중요한 단계는 window의 rootViewController를 탭 바 컨트롤러로 설정하는 것입니다. 그래야 탭 바가 각 탭 항목 안의 내비게이션 컨트롤러와 함께 앱 계층 구조의 최상단에 자리 잡습니다.
뷰 컨트롤러 동작 확인
아래 ViewController 클래스를 살펴봅시다.
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
}
func setupUI(){
view.backgroundColor = .white
let homeLabel: UILabel = {
let label = UILabel()
label.text = "This is home screen"
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
let homeButton: UIButton = {
let button = UIButton()
button.setTitle("Go to profile", for: .normal)
button.setTitleColor(.white, for: .normal)
button.backgroundColor = .systemOrange
button.translatesAutoresizingMaskIntoConstraints = false
button.addTarget(self, action: #selector(goToProfile), for: .touchUpInside)
return button
}()
view.addSubview(homeButton)
view.addSubview(homeLabel)
NSLayoutConstraint.activate([
homeButton.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor),
homeButton.widthAnchor.constraint(equalTo: view.widthAnchor),
homeButton.heightAnchor.constraint(equalToConstant: 72),
homeLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor),
homeLabel.centerYAnchor.constraint(equalTo: view.centerYAnchor)
])
}
@objc func goToProfile(){
tabBarController?.selectedIndex = 1
}
}
그리고 SecondViewController입니다(네, 이름 짓기가 형편없다는 거 압니다…)

class SecondViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
}
func setupUI(){
view.backgroundColor = .white
let profileLabel: UILabel = {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.text = "This is profile screen"
return label
}()
let profileButton: UIButton = {
let button = UIButton()
button.setTitle("Go to home", for: .normal)
button.setTitleColor(.white, for: .normal)
button.backgroundColor = .systemOrange
button.translatesAutoresizingMaskIntoConstraints = false
button.addTarget(self, action: #selector(goToHome), for: .touchUpInside)
return button
}()
view.addSubview(profileButton)
view.addSubview(profileLabel)
NSLayoutConstraint.activate([
homeButton.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor),
homeButton.widthAnchor.constraint(equalTo: view.widthAnchor),
homeButton.heightAnchor.constraint(equalToConstant: 72),
homeLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor),
homeLabel.centerYAnchor.constraint(equalTo: view.centerYAnchor)
])
}
@objc func goToHome(){
tabBarController?.selectedIndex = 0
}
}
보시다시피 코드가 꽤 반복적입니다. 하지만 이 글의 목적상 넘어가도 괜찮습니다.
두 뷰 컨트롤러는 제목과 버튼 동작만 빼면 사실상 똑같습니다. 둘 다 화면 가운데에 현재 화면의 이름을 알려 주는 레이블을 그립니다. 또 화면 아래쪽에 탭 항목 사이를 이동할 수 있는 버튼이 있습니다. 이 뷰 컨트롤러들의 핵심 기능은 이것이 전부입니다.
최종 결과
이제 스토리보드를 하나도 쓰지 않고 탭 바와 내비게이션 컨트롤러를 사용하는, 완전히 코드로 만든 앱이 생겼습니다!

마치며
정리하면, 코드 방식을 택하면 앱의 디자인과 확장성을 더 잘 통제할 수 있고, 개발자가 스토리보드에만 의존하지 않고 프로그래밍 자체에 집중할 수 있습니다. 특히 IBAction/IBOutlet 문제가 그렇습니다. IBOutlet과 IBAction 변수가 얽힌 코드를 리팩터링할 때 생기는 대표적인 문제는, 수정한 뒤에 연결을 다시 맺어 줘야 한다는 것입니다. 제 경험상 코드베이스에서 며칠 작업하고 나면 아무런 설명 없이 앱이 갑자기 크래시되곤 했습니다. 더 파고들어 보니 원인은 이름을 바꾼 IBOutlet과 IBAction 변수였습니다. 그럴 때마다 영향을 받은 변수들을 손으로 다시 연결해야 기능이 돌아왔습니다. 이는 시간도 많이 들고 짜증스러운 과정이며 개발 흐름을 끊어 놓습니다.
읽어 주셔서 감사합니다!