2

I have the following basic utilization of NavigationStack with SwiftUI for iOS 16, Xcode.

The issues I am facing is that when I click back and printing the count, the root count is wrong and shows as "1" instead of always showing as "0".

Why and how to fix?

import SwiftUI

struct SettingsLink: Hashable {
    let name: String
}
struct NotificationsLink: Hashable {
    let name: String
}

struct ContentView: View {
    
    var settingsLink: [SettingsLink] = [.init(name: "Settings")]
    var notificationsLink: [NotificationsLink] = [.init(name: "Notifications")]
    
    @State private var path = NavigationPath()
    
    var body: some View {
        
        NavigationStack(path: $path) {
            
            VStack {
                NavigationLink(value: settingsLink[0]) {
                    Text(settingsLink[0].name)
                }
                NavigationLink(value: notificationsLink[0]) {
                    Text(notificationsLink[0].name)
                }
            }
            .onAppear() {
                print("Root Should Always be Zero: \(path.count)")
            }
            .navigationDestination(for: SettingsLink.self) {
                settingsLink in
                VStack {
                    Text("\(settingsLink.name)")
                }
                .onAppear() {
                    print("Settings: \(path.count)")
                }
            }
            .navigationDestination(for: NotificationsLink.self) {
                notificationsLink in
                VStack {
                    Text("\(notificationsLink.name)")
                }
                .onAppear() {
                    print("Notifications: \(path.count)")
                }
            }
        }
    }

}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }

}

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.