44: Navigation, part 2

그루두·2024년 6월 17일
0

100 days of SwiftUI

목록 보기
52/108
post-thumbnail

100 days of swiftui: 44

NavigationStack with path(programmatic navigation)

Navigation의 path를 임의로 설정해서 화면과 화면을 이동시킬 수 있다.

struct ContentView: View {
    @State private var path = [Int]()
    var body: some View {
        NavigationStack(path: $path) {
            VStack {
                Button("go to 10") {
                    path = [10]
                }
                Button("go to 100") {
                    path.append(100)
                }
                Button("go to 30 and 10, 100") {
                    path = [30, 10, 100]
                }
            }
            .navigationDestination(for: Int.self) { selection in
                Text("This is \(selection)")
            }
        }
    }
}

깃헙 링크

Navigation with different data types

NavigationPath를 사용해 single path에 다른 데이터 타입의 path를 함께 이용할 수 있다.

아래 예시는 Int와 String 데이터 타입을 path로 사용한다. 이때 각각 navigationDestination를 설정하면 된다.

struct ContentView: View {
    @State private var path = NavigationPath()
    var body: some View {
        NavigationStack(path: $path) {
            List {
                ForEach(1..<6) { i in
                    NavigationLink("number: \(i)", value: i)
                }
                ForEach(1..<6) { i in
                    NavigationLink("string: \(i)", value: String(i))
                }
            }
            .navigationDestination(for: Int.self) { selection in
                Text("number \(selection)")
            }
            .navigationDestination(for: String.self) { selection in
                Text("string \(selection)")
            }
        }
    }
}

깃헙 링크

추가로 toolbar에서도 path를 지정할 수 있다.

// ...
            .toolbar {
                Button("Push path 200") {
                    path.append(200)
                }
                Button("Push path 50") {
                    path.append(50)
                }
            }

깃헙 링크

return to root view

NavigationLink로 여러 화면을 이동하고 한 번에 모든 경로를 지우고 원래 화면으로 돌아오도록 설정할 수 있다.

먼저, 무작위 숫자가 설정되고 그 값을 path로 이동하는 NavigationView를 설정한다. NavigationPath인 path와 path의 값인 num을 속성으로 지닌다.

struct NavigationView: View {
    var num: Int
    @Binding var path: NavigationPath
    var body: some View {
        NavigationLink("Going to random NavigationView", value: Int.random(in: 0...1000))
            .navigationTitle("number \(num)")
    }
}

그리고 NavigationView를 NavigationStack에 나타낸다. 초기 값은 0으로 설정하고 해당 뷰의 navigationDestination을 아래로 설정한다. NavigationView에서 다음 path는 무작위 숫자로 설정되니 selection인 i를 다음 NavigationViewnum으로 넘기면 된다.

struct ContentView: View {
    @State private var path = NavigationPath()
    var body: some View {
        NavigationStack(path: $path) {
            NavigationView(num: 0, path: $path)
                .navigationDestination(for: Int.self) { i in
                    NavigationView(num: i, path: $path)
                }
        }
    }
}

깃헙 링크

그리고 마지막으로 NavigationPath를 초기화하는 버튼은 toolbar에 추가하면 된다.

            .toolbar {
                Button("Going home") {
                    path = NavigationPath()
                }
            }

깃헙 링크

NavigationPath 저장하기

How to save NavigationStack paths using Codable

오늘의 마지막 강의는 지금 이해하기 어렵다. 얼추 이해한 바만 정리해보자면, Codable 그러니까 JSON으로 encode & decode하여 path가 변경되는 순간에 저장하고 불러오는 형태로 path를 기록한다. 그래서 앱을 종료하고 다시 실행해도 옮겨다닌 path가 그대로 나타난다.

깃헙 링크

profile
계속 해보자

0개의 댓글

관련 채용 정보