Search code examples
swiftuiswiftui-navigationlink

Unable to seque to new view with navigationlink


I am attempting to create a segue from one view to another in SwiftUI with NavigationLink but so far have been unable to get this to work. Here is the code I'm working with:

                
                
                VStack(spacing: 40) {
                    
                    Button("Management") {
                        // Need Code here
                        
                        NavigationLink(destination: TestView()) {
                                            Label("Test", systemImage: "timer")
                                                .font(.headline)
                                                .foregroundColor(.accentColor)
                                        }
                    }
                    
                    Button("Calculator") {
                        // Need Code here
                        
                    }
                }

I have a warning that shows up on the Navlink which is Result of 'NavigationLink<Label, Destination>' initializer is unused

When I click the button nothing happens. I have tried to use the navigation link outside the button as well and still get nothing.

Here is the code the TestView:

import SwiftUI

struct TestView: View {
    var body: some View {
        Text(/*@START_MENU_TOKEN@*/"Hello, World!"/*@END_MENU_TOKEN@*/)
    }
}

#Preview {
    TestView()
}

Any help would be appreciated.


Solution

  • It's because NavigationLink is a View, and you're declaring a View without using it. The Label content is also meaningless. You can unwrap it from Button action.

    Beside this, you'll need NavigationStack outside to make the NavigationLink work.

    NavigationStack { //<- here
        VStack(spacing: 40) {
            NavigationLink(destination: TestView()) { //<- here
                Text("Management")
            }
        }
    }