SwiftUI 탐색
이 스킬을 사용해야 하는 경우
다음과 같은 경우에 사용합니다:
- 탐색 아키텍처 선택 (NavigationStack vs NavigationSplitView vs TabView)
- NavigationPath를 사용한 프로그래밍 방식 탐색 구현
- 딥 링크 및 URL 라우팅 설정
- 탐색 상태 복원 구현
- 탭/사이드바 패턴 도입 (iOS 18+)
- 코디네이터/라우터 패턴 구현
- 배포 전 탐색 구현 코드 리뷰 요청
관련 스킬
axiom-swiftui-nav-diag: 탐색 실패의 체계적인 문제 해결에 사용axiom-swiftui-nav-ref: 모든 WWDC 예제와 함께 포괄적인 API 참조 제공 (탭 사용자 정의, iOS 26+ 기능 포함)
예제 프롬프트
이 스킬이 답변하도록 설계된 개발자들이 실제로 묻는 질문입니다:
1. "내 앱에 NavigationStack 또는 NavigationSplitView를 사용해야 하나요?"
-> 이 스킬은 기기 대상, 콘텐츠 계층 깊이 및 멀티플랫폼 요구 사항을 기반으로 한 의사 결정 트리를 제공합니다.
2. "SwiftUI에서 프로그래밍 방식으로 탐색하려면 어떻게 해야 하나요?"
-> 이 스킬은 푸시, 팝, 팝-투-루트 및 딥 링크를 위한 NavigationPath 조작 패턴을 보여줍니다.
3. "딥 링크가 작동하지 않습니다. 앱이 열리지만 잘못된 화면이 표시됩니다."
-> 이 스킬은 URL 구문 분석 패턴, 경로 구성 순서 및 onOpenURL 타이밍 문제를 다룹니다.
4. "앱이 백그라운드로 전환될 때 탐색 상태가 손실됩니다."
-> 이 스킬은 Codable NavigationPath, SceneStorage 지속성 및 충돌 방지 복원을 보여줍니다.
5. "SwiftUI에서 코디네이터 패턴을 구현하려면 어떻게 해야 하나요?"
-> 이 스킬은 코디네이터가 가치를 더하는 경우와 복잡성을 더하는 경우에 대한 지침과 함께 라우터 패턴 예제를 제공합니다.
위험 신호 — 방지해야 할 안티 패턴
다음 중 하나라도 수행 중이라면 중단하고 이 스킬의 패턴을 사용하세요:
❌ 중요 — 절대 하지 말아야 할 것
1. iOS 16+에서 사용 중단된 NavigationView 사용
// ❌ 잘못됨 — iOS 16+에서 사용 중단, 다른 동작
NavigationView {
List { ... }
}
.navigationViewStyle(.stack)
실패 이유 NavigationView는 iOS 16부터 사용 중단되었습니다. NavigationPath를 지원하지 않아 프로그래밍 방식 탐색과 딥 링크를 신뢰할 수 없게 만듭니다. iOS 버전 간 다른 동작으로 인해 버그가 발생합니다.
2. 프로그래밍 방식 탐색을 위해 뷰 기반 NavigationLink 사용
// ❌ 잘못됨 — 프로그래밍 방식으로 제어 불가능
NavigationLink("Recipe") {
RecipeDetail(recipe: recipe) // 뷰 대상, 값 없음
}
실패 이유 뷰 기반 링크는 프로그래밍 방식으로 제어할 수 없습니다. 이 대상에 딥 링크하거나 팝할 방법이 없습니다. iOS 16부터 사용 중단되었습니다.
3. 지연 컨테이너 내부에 navigationDestination 배치
// ❌ 잘못됨 — 필요할 때 로드되지 않을 수 있음
LazyVGrid(columns: columns) {
ForEach(items) { item in
NavigationLink(value: item) { ... }
.navigationDestination(for: Item.self) { item in // 이렇게 하지 마세요
ItemDetail(item: item)
}
}
}
실패 이유 지연 컨테이너는 모든 뷰를 즉시 로드하지 않습니다. navigationDestination이 NavigationStack에 보이지 않아 탐색이 자동으로 실패할 수 있습니다.
4. 복원을 위해 NavigationPath에 전체 모델 객체 저장
// ❌ 잘못됨 — 데이터 중복, 복원 시 오래된 데이터
class NavigationModel: Codable {
var path: [Recipe] = [] // 전체 Recipe 객체
}
실패 이유 이미 모델에 있는 데이터를 중복합니다. 복원 시 Recipe 데이터가 (다른 곳에서 편집/삭제되어) 오래된 것일 수 있습니다. ID를 사용하고 현재 데이터로 해결하세요.
5. MainActor 외부에서 NavigationPath 수정
// ❌ 잘못됨 — 메인 스레드가 아닌 UI 업데이트
Task.detached {
await viewModel.path.append(recipe) // 백그라운드 스레드
}
실패 이유 NavigationPath는 UI에 바인딩됩니다. 수정은 MainActor에서 발생해야 하며, 그렇지 않으면 탐색 상태가 손상됩니다. 충돌 또는 자동 실패를 유발할 수 있습니다.
6. 탐색 상태에 대한 @MainActor 격리 누락
// ❌ 잘못됨 — MainActor 격리되지 않음
class Router: ObservableObject {
@Published var path = NavigationPath() // @MainActor 없음
}
실패 이유 Swift 6의 엄격한 동시성에서 SwiftUI 뷰에서 액세스하는 @Published 속성은 MainActor 격리가 필요합니다. 데이터 경합 경고와 잠재적인 충돌을 유발합니다.
7. 다중 탭 앱에서 탐색 상태 처리 안 함
// ❌ 잘못됨 — 탭 간에 공유되는 NavigationPath
TabView {
Tab("Home") { HomeView() }
Tab("Settings") { SettingsView() }
}
// 모든 탭이 동일한 NavigationStack을 공유합니다 — 잘못됨!
실패 이유 각 탭은 고유한 NavigationStack을 가져 탭 전환 시 탐색 상태를 유지해야 합니다. 공유 상태는 혼란스러운 사용자 경험을 유발합니다.
8. NavigationPath 디코딩 오류 무시
// ❌ 잘못됨 — 유효하지 않은 데이터에서 충돌
let path = NavigationPath(try! decoder.decode(NavigationPath.CodableRepresentation.self, from: data))
실패 이유 사용자가 경로에 있던 항목을 삭제했을 수 있습니다. 스키마가 변경되었을 수 있습니다. 강제 언래핑은 복원 시 충돌을 유발합니다.
필수 첫 단계
탐색을 구현하기 전에 항상 다음 단계를 완료하세요:
// 단계 1: 탐색 구조 식별
// 질문: 단일 스택? 다중 열? 탭 기반 및 탭별 탐색?
// 코드를 작성하기 전에 답변을 기록하세요
// 단계 2: 구조에 따라 컨테이너 선택
// 단일 스택(iPhone-primary): NavigationStack
// 다중 열(iPad/Mac-primary): NavigationSplitView
// 탭 기반: 탭당 NavigationStack이 있는 TabView
// 단계 3: 탐색을 위한 값 유형 정의
// NavigationStack에 푸시된 모든 값은 Hashable이어야 함
// 딥 링크/복원을 위해서는 Codable도 필요
struct Recipe: Hashable, Codable, Identifiable { ... }
// 단계 4: 딥 링크 URL 계획 (필요한 경우)
// myapp://recipe/{id}
// myapp://category/{name}/recipe/{id}
// 단계 5: 상태 복원 계획 (필요한 경우)
// SceneStorage를 사용할 것인가? 어떤 데이터가 Codable이어야 하는가?
빠른 의사 결정 트리
탐색이 필요한가?
├─ 다중 열 인터페이스(iPad/Mac primary)?
│ └─ NavigationSplitView
│ ├─ 세부 열에 드릴다운 필요?
│ │ └─ 세부 내부의 NavigationStack (패턴 3)
│ └─ 선택 전용 세부?
│ └─ 선택 바인딩만 (패턴 2)
├─ 탭 기반 앱?
│ └─ TabView
│ ├─ 각 탭에 드릴다운 필요?
│ │ └─ 탭당 NavigationStack (패턴 4)
│ └─ iPad 사이드바 경험?
│ └─ .tabViewStyle(.sidebarAdaptable) (패턴 5)
└─ 단일 열 스택?
└─ NavigationStack
├─ 딥 링크 필요?
│ └─ NavigationPath 사용 (패턴 1b)
└─ 간단한 푸시/팝?
└─ 타입화된 배열 경로 (패턴 1a)
상태 복원이 필요한가?
└─ SceneStorage + Codable NavigationPath (패턴 6)
코디네이터 추상화가 필요한가?
├─ 복잡한 조건부 흐름?
├─ 탐색 로직 테스트 필요?
├─ 여러 화면에서 탐색 공유?
└─ 위 중 하나라도 YES → 라우터 패턴 (패턴 7)
모두 NO → NavigationPath 직접 사용
패턴 1a: 기본 NavigationStack
사용 시기: 간단한 푸시/팝 탐색, 모든 대상이 동일한 유형
소요 시간: 5-10분
struct RecipeList: View {
@State private var path: [Recipe] = []
var body: some View {
NavigationStack(path: $path) {
List(recipes) { recipe in
NavigationLink(recipe.name, value: recipe)
}
.navigationTitle("Recipes")
.navigationDestination(for: Recipe.self) { recipe in
RecipeDetail(recipe: recipe)
}
}
}
// 프로그래밍 방식 탐색
func showRecipe(_ recipe: Recipe) {
path.append(recipe)
}
func popToRoot() {
path.removeAll()
}
}
핵심 포인트:
- 모든 값이 동일한 유형일 때 타입화된 배열
[Recipe] - 값 기반
NavigationLink(title, value:) - 지연 컨테이너 외부의
navigationDestination(for:)
패턴 1b: 딥 링크가 있는 NavigationStack
사용 시기: 여러 대상 유형, URL 기반 딥 링크
소요 시간: 15-20분
struct ContentView: View {
@State private var path = NavigationPath()
var body: some View {
NavigationStack(path: $path) {
HomeView()
.navigationDestination(for: Category.self) { category in
CategoryView(category: category)
}
.navigationDestination(for: Recipe.self) { recipe in
RecipeDetail(recipe: recipe)
}
}
.onOpenURL { url in
handleDeepLink(url)
}
}
func handleDeepLink(_ url: URL) {
// URL: myapp://category/desserts/recipe/apple-pie
path.removeLast(path.count) // 먼저 루트로 팝
guard let components = URLComponents(url: url, resolvingAgainstBaseURL: false) else { return }
let segments = components.path.split(separator: "/").map(String.init)
var index = 0
while index < segments.count - 1 {
switch segments[index] {
case "category":
if let category = Category(rawValue: segments[index + 1]) {
path.append(category)
}
index += 2
case "recipe":
if let recipe = dataModel.recipe(named: segments[index + 1]) {
path.append(recipe)
}
index += 2
default:
index += 1
}
}
}
}
핵심 포인트:
- 이기종 유형을 위한
NavigationPath - 딥 링크 경로를 구축하기 전에 루트로 팝
- 올바른 순서로 경로 구축 (부모 → 자식)
패턴 2: NavigationSplitView 선택 기반
사용 시기: 세부 항목에 선택된 항목을 표시하는 다중 열 레이아웃
소요 시간: 10-15분
struct MultiColumnView: View {
@State private var selectedCategory: Category?
@State private var selectedRecipe: Recipe?
var body: some View {
NavigationSplitView {
List(Category.allCases, selection: $selectedCategory) { category in
NavigationLink(category.name, value: category)
}
.navigationTitle("Categories")
} content: {
if let category = selectedCategory {
List(recipes(in: category), selection: $selectedRecipe) { recipe in
NavigationLink(recipe.name, value: recipe)
}
.navigationTitle(category.name)
} else {
Text("Select a category")
}
} detail: {
if let recipe = selectedRecipe {
RecipeDetail(recipe: recipe)
} else {
Text("Select a recipe")
}
}
}
}
핵심 포인트:
- List의
selection: $binding이 열 선택과 연결됨 - 값을 제시하는 링크가 선택을 자동으로 업데이트
- iPhone에서 단일 스택으로 적응
패턴 3: 다중 열 세부에 스택이 있는 NavigationSplitView
사용 시기: 세부 항목에서 드릴다운 기능이 있는 다중 열
소요 시간: 20-25분
struct GridWithDrillDown: View {
@State private var selectedCategory: Category?
@State private var path: [Recipe] = []
var body: some View {
NavigationSplitView {
List(Category.allCases, selection: $selectedCategory) { category in
NavigationLink(category.name, value: category)
}
.navigationTitle("Categories")
} detail: {
NavigationStack(path: $path) {
if let category = selectedCategory {
RecipeGrid(category: category)
.navigationDestination(for: Recipe.self) { recipe in
RecipeDetail(recipe: recipe)
}
} else {
Text("Select a category")
}
}
}
}
}
핵심 포인트:
- 세부 열 내부의 NavigationStack
- 사이드바를 유지하면서 그리드 → 세부 드릴다운
- 드릴다운을 위한 별도 경로, 사이드바를 위한 선택
패턴 4: 탭별 NavigationStack이 있는 TabView
사용 시기: 각 탭에 고유한 탐색이 있는 탭 기반 앱
소요 시간: 15-20분
struct TabBasedApp: View {
var body: some View {
TabView {
Tab("Home", systemImage: "house") {
NavigationStack {
HomeView()
.navigationDestination(for: Item.self) { item in
ItemDetail(item: item)
}
}
}
Tab("Search", systemImage: "magnifyingglass") {
NavigationStack {
SearchView()
}
}
Tab("Settings", systemImage: "gear") {
NavigationStack {
SettingsView()
}
}
}
}
}
핵심 포인트:
- 각 탭은 고유한 NavigationStack을 가짐
- 탭 전환 시 탐색 상태 유지
- systemImage가 있는 iOS 18+ Tab 구문
패턴 5: 사이드바 적응형 TabView (iOS 18+)
사용 시기: iPhone에서는 탭 바, iPad에서는 사이드바
소요 시간: 20-25분
struct AdaptableApp: View {
var body: some View {
TabView {
Tab("Watch Now", systemImage: "play") {
WatchNowView()
}
Tab("Library", systemImage: "books.vertical") {
LibraryView()
}
TabSection("Collections") {
Tab("Favorites", systemImage: "star") {
FavoritesView()
}
Tab("Recently Added", systemImage: "clock") {
RecentView()
}
}
Tab(role: .search) {
SearchView()
}
}
.tabViewStyle(.sidebarAdaptable)
}
}
핵심 포인트:
.tabViewStyle(.sidebarAdaptable)이 iPad에서 사이드바 활성화TabSection이 사이드바에서 접을 수 있는 그룹 생성Tab(role: .search)가 특별한 배치를 얻음
패턴 6: 상태 복원
사용 시기: 앱이 백그라운드로 전환되거나 종료된 후 탐색 상태 유지
소요 시간: 20-30분
struct StateRestorableApp: View {
@SceneStorage("navigationPath") private var pathData: Data = Data()
@State private var path = NavigationPath()
var body: some View {
NavigationStack(path: $path) {
ContentView()
}
.onAppear {
restorePath()
}
.onChange(of: path) {
savePath()
}
}
private func savePath() {
guard let representation = path.codable else { return }
do {
let data = try JSONEncoder().encode(representation)
pathData = data
} catch {
// 저장 실패 처리 — 경로를 지우는 것이 안전
pathData = Data()
}
}
private func restorePath() {
guard !pathData.isEmpty else { return }
do {
let representation = try JSONDecoder().decode(
NavigationPath.CodableRepresentation.self,
from: pathData
)
path = NavigationPath(representation)
} catch {
// 복원 실패 처리 — 손상된 데이터 무시
pathData = Data()
}
}
}
핵심 포인트:
- 미리보기 및 테스트를 위해
@SceneStorage사용 —@AppStorage보다 나음 - 오류를 포착하고 자동 충돌 대신 빈 경로로 fallback
NavigationPath.CodableRepresentation로 직렬화- 필터링되지 않은 관찰을 위해
onChange(of:)사용 (Swift 5.9+)
패턴 7: 라우터 패턴
사용 시기: 복잡한 조건부 흐름 또는 테스트 가능한 탐색 로직
소요 시간: 20-30분
// 1. 라우터 프로토콜 정의
@MainActor
protocol Routing {
func navigate(to destination: AppDestination)
func pop()
func popToRoot()
}
// 2. 열거형 대상
enum AppDestination: Hashable {
case home
case recipe(Recipe)
case category(Category)
case settings
}
// 3. 라우터 구현
@MainActor
class AppRouter: ObservableObject, Routing {
@Published var path = NavigationPath()
func navigate(to destination: AppDestination) {
path.append(destination)
}
func pop() {
guard !path.isEmpty else { return }
path.removeLast()
}
func popToRoot() {
path.removeLast(path.count)
}
}
// 4. 환경에 주입
struct AppView: View {
@State private var router = AppRouter()
var body: some View {
NavigationStack(path: $router.path) {
HomeView()
.navigationDestination(for: AppDestination.self) { destination in
switch destination {
case .home:
HomeView()
case .recipe(let recipe):
RecipeDetail(recipe: recipe)
case .category(let category):
CategoryView(category: category)
case .settings:
SettingsView()
}
}
}
.environmentObject(router)
}
}
핵심 포인트:
@MainActor는 Router 클래스가 Swift 6 동시성을 충족하도록 보장- Destination 열거형은 Codable + Hashable일 수 있어 복원 지원
@Published var path = NavigationPath()는 SwiftUI 업데이트를 트리거- 프리뷰에서 테스트를 위해 MockRouter를 주입하여 프로토콜이 가치를 더함
iOS 버전 호환성 참조
| 패턴 | iOS 최소 버전 | 메모 |
|---|---|---|
| NavigationStack (패턴 1) | iOS 16 | iOS 15에서는 NavigationView 사용 |
| NavigationSplitView (패턴 2) | iOS 16 | iOS 15에서는 NavigationView |
| sidebarAdaptable (패턴 5) | iOS 18 | 이전 버전에서는 .tabViewStyle(.sidebar) |
| TabSection (패턴 5) | iOS 18 | iOS 18 전용 |
| SceneStorage 복원 (패턴 6) | iOS 14 | iOS 17+에서 더 안정적임 |
| 딥 링크 (패턴 1b) | iOS 14 | onOpenURL은 iOS 14+ |
마이그레이션 가이드
NavigationView에서 NavigationStack으로 (iOS 16+)
// 이전 (사용 중단됨)
NavigationView {
ContentView()
}
.navigationViewStyle(.stack)
// 이후 (iOS 16+)
NavigationStack {
ContentView()
}
UIKit UINavigationController에서 (SwiftUI 도입)
// UIKit 스타일 (이전)
let vc = UINavigationController(rootViewController: listVC)
vc.pushViewController(detailVC, animated: true)
// SwiftUI 스타일 (이후)
NavigationStack(path: $path) {
ListView()
.navigationDestination(for: Item.self) { item in
DetailView(item: item)
}
}
// path.append(item)로 푸시
문제 해결 가이드
| 증상 | 가능한 원인 | 해결 방법 |
|---|---|---|
| NavigationLink가 작동하지 않음 | navigationDestination이 지연 컨테이너 내부에 있음 | navigationDestination을 Lazy 컨테이너 외부로 이동 |
| 딥 링크가 잘못된 화면 표시 | 경로 순서가 잘못됨 (자식이 부모보다 먼저) | 올바른 순서로 경로 구축: 부모, 그 다음 자식 |
| 상태 복원이 앱을 충돌시킴 | 강제 언래핑된 디코드 | do/try/catch 사용, 오류 시 빈 경로로 fallback |
| 탭 전환 시 탐색 손실됨 | 탭 간에 공유된 NavigationStack | 각 탭에 고유한 NavigationStack 부여 |
| 탐색이 메모리에서 해제된 화면 표시 | NavigationPath의 약한 참조 | NavigationPath에 Hashable 값 사용 (참조 아님) |
| Swift 6 동시성 경고 | @MainActor 누락 | Router/ViewModel 클래스에 @MainActor 추가 |
예제
1. 항목 목록이 있는 기본 NavigationStack
사용자 요청: "간단한 푸시/팝이 있는 레시피 목록"
struct RecipeListView: View {
@State private var path: [Recipe] = []
var body: some View {
NavigationStack(path: $path) {
List(Recipe.samples) { recipe in
NavigationLink(recipe.name, value: recipe)
}
.navigationDestination(for: Recipe.self) { recipe in
RecipeDetailView(recipe: recipe)
}
.toolbar {
Button("Random Recipe") {
path.append(Recipe.samples.randomElement()!)
}
}
}
}
}
struct RecipeDetailView: View {
let recipe: Recipe
@Environment(\.dismiss) private var dismiss
var body: some View {
VStack {
Text(recipe.name).font(.title)
Text(recipe.instructions)
Button("Go Back") { dismiss() }
}
.navigationTitle(recipe.name)
}
}
2. NavigationSplitView를 탭 앱에 통합
사용자 요청: "iPad에서 사이드바가 있는 탭 앱"
// iPad에서 사이드바로 표시, iPhone에서 탭 바
TabView {
Tab("Library", systemImage: "books.vertical") {
NavigationSplitView {
SidebarView()
} detail: {
LibraryContentView()
}
}
Tab("Search", systemImage: "magnifyingglass") {
NavigationStack {
SearchView()
}
}
}
.tabViewStyle(.sidebarAdaptable)
이 접근 방식은 각 주요 섹션에 대해 NavigationSplitView를 사용하면서 앱 수준에서 사이드바 적응형 탭 바를 사용합니다. TabSection을 사용하여 사이드바의 섹션을 그룹화할 수 있습니다 (iOS 18+).
3. 딥 링크로 커스텀 URL 스킴 처리
사용자 요청: "내 앱이 myapp://recipe/123을 여는 딥 링크 지원"
@main
struct MyApp: App {
var body: some Scene {
WindowGroup {
ContentView()
.onOpenURL { url in
NotificationCenter.default.post(
name: .handleDeepLink,
object: url
)
}
}
}
}
// ContentView에서:
struct ContentView: View {
@State private var path = NavigationPath()
var body: some View {
NavigationStack(path: $path) {
HomeView()
.navigationDestination(for: Recipe.self) { recipe in
RecipeDetailView(recipe: recipe)
}
}
.onReceive(NotificationCenter.default.publisher(for: .handleDeepLink)) { notification in
guard let url = notification.object as? URL else { return }
path.removeLast(path.count)
if let recipe = parseRecipe(from: url) {
path.append(recipe)
}
}
}
func parseRecipe(from url: URL) -> Recipe? {
guard url.scheme == "myapp",
url.host == "recipe",
let id = Int(url.pathComponents.last ?? "")
else { return nil }
return Recipe(id: id)
}
}
4. State Restorat…
[번역을 위해 잘림]