1

I am making an app where I need to navigate to the home page when the user clicks on the Login button and when the Login button is clicked, the navigation link code is not working and shows a warning as Result of 'NavigationLink<Label, Destination>' initializer is unused. FYI, please refer to the attached screenshot and the below code:

import SwiftUI

struct LoginView: View {

    var nextButton: some View {
        HStack {
            Button("Next") {
                NavigationLink {
                    HomeView(user: user)
                } label: {
                    Text("Test")
                }

            }
            .buttonStyle(PlainButtonStyle())
            .font(.system(size: 24))
        }
    }

    var body: some View {
        NavigationStack {
            nextButton
        }
    }

}

enter image description here

Jatin Bhuva
  • 1,301
  • 1
  • 4
  • 22
Subbu
  • 41
  • 1
  • 4
  • `NavigationLink`s don't go inside a `Button`'s `action` -- the `action` is for imperative code, not `View` hierarchy elements. Remove the `Button` and just use the `NavigationLink` – jnpdx Dec 28 '22 at 04:37
  • Why are you using `NavigationLink` at first place inside a `Button`? Use only NL and make the UI like a `Button` or use a `@State Bool` and use it on NavigationLink's `isActive` parameter. – Neck Dec 28 '22 at 06:23

1 Answers1

0

There are two problems here:

  1. A NavigationLink is an alternative to a Button and can be used on its own for navigation. You can use a button to navigate programatically, but for this simple case a link works. Like Buttons, you can change the appearance of NavigationLinks if needed.

  2. NavigationStack is a more powerful replacement for NavigationView. You should not mix them both. As the HomeView is your root view, the single NavigationStack for your app should be there (not in the LoginView).

struct HomeView: View {
    var body: some View {
        NavigationStack {
            VStack {
                NavigationLink {
                    LoginView()
                } label: {
                    Text("Login")
                }
            }
        }
    }
}

The warning is because you are creating a NavigationLink in the button action code block, and returned NavigationLink is not assigned or used.

TheGeneEng
  • 11
  • 3