# NavigationStackの注意点 ## NavigationStackを使ったコード ```swift= struct RootView: View { var body: some View { NavigationStack { VStack(spacing: 16) { NavigationLink("green", value: Color.green) NavigationLink("gray", destination: ColorView(color: .gray)) } .frame(maxWidth: .infinity, maxHeight: .infinity) .navigationDestination(for: Color.self) { value in ColorView(color: value) } .navigationTitle(Text("White")) } } } struct ColorView: View { let color: Color var body: some View { VStack(spacing: 16) { NavigationLink("green", value: Color.green) .foregroundColor(.white) NavigationLink("gray", destination: ColorView(color: .gray)) .foregroundColor(.white) } .frame(maxWidth: .infinity, maxHeight: .infinity) .background(color) .navigationTitle(Text(color.description)) } } struct Previews: PreviewProvider { static var previews: some View { RootView() } } ``` ## 挙動がおかしい? | 初期画面 | grayを押す | greenを押す | Stackがおかしい | | -------- | -------- | -------- | -------- | || | || 本来white -> gray -> greenと画面遷移をしたはずがwhite -> green -> grayになってしまった。 ## 挙動検証 NavigationStackの挙動を検証するためにNavigationStackのpathがどう変化するかみてみる まずpathの変化を監視するために以下のコードを書く ```swift= class NavigationObject: ObservableObject { @Published var path: NavigationPath = .init() { didSet { print(path) } } } struct RootView: View { @StateObject var o = NavigationObject() var body: some View { NavigationStack(path: $o.path) { ... } } } ``` ### white -> grayの画面遷移時 結果: 何もprintされない。つまりpathは変化してない ### gray -> greenの画面遷移時 結果: `NavigationPath(_items: SwiftUI.NavigationPath.(unknown context at $106a682b8).Representation.eager([SwiftUI.(unknown context at $106a67ee8).ItemBox<SwiftUI.Color>]), subsequentItems: [], iterationIndex: 0)` pathが追加された ## まとめ NavigationStackを使ってもpathに追加される書き方とそうではない書き方がある。 | pathに追加される | pathに追加されない | | -------- | -------- | | NavigationLink(_ title,value:)|NavigationLink(_ title, destination:)| **これらを同じNavigationStack下で混ぜて書くとバグるの注意!**
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up