1

How can I build a list of navigation list using ForEach in SwiftUI. I thought of something like below but it doesn't work.

struct ContentView: View {
  
  var menuButtons = ["Profile", "About Us", "Contact Us"]
  
    var body: some View {
        
      ForEach(menuButtons, id:\.self) {menu in
        NavigationView(content: {
          NavigationLink(destination: {
            if menu == "Profile" {
              Profile()
            }
            if menu == "About Us" {
              AboutUs()
            }
          }) { Text(menu) }
        })
      }
    }
}

1 Answer 1

3
  1. Move the NavigationView outside the ForEach, otherwise you'll have multiple navigation views.
  2. You also want a VStack that wraps the ForEach, so the navigation links are stacked.
  3. Wrap the if statements inside a Group to group it into a single View, which the destination expects.
struct ContentView: View {
    var menuButtons = ["Profile", "About Us", "Contact Us"]
    
    var body: some View {
        NavigationView { /// 1.
            VStack { /// 2.
                ForEach(menuButtons, id: \.self) { menu in
                    NavigationLink(
                        destination:
                            Group { /// 3.
                                if menu == "Profile" {
                                    Profile()
                                }
                                if menu == "About Us" {
                                    AboutUs()
                                }
                            }
                    ) {
                        Text(menu)
                    }
                }
            }
        }
    }
}

Result:

Home page (ContentView) After clicking a navigation link
"Profile", "About Us", and "Contact Us" stacked vertically Profile view displayed with back button to go back
Sign up to request clarification or add additional context in comments.

2 Comments

In the front page, how can the list be shown so user can select to go profile or about us...
@DarylWong I added an image, is that what you want?

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.