Search code examples
iosswiftswiftuiswiftui-listswiftui-navigationlink

How to add navigation button link in button in SwiftUI?


I want to nagivate to the details screen using button. the buttons are designed in a separate view and called Using ForEach function. Please guide me to solve this.

This is the code I designed for button

struct ButtonsDesignView: View {

var buttons: MyModel.buttons
var body: some View {

        Button(action: { }) {
        ZStack {
            HStack{
                VStack{
            Text(btn.title)
                .foregroundColor(Color(.blue))
                .padding()
            
          Text(btn.subtitle)
                .foregroundColor(Color(.blue))
            .padding()
                }
                Spacer()
                VStack{
                    Image(systemName: (btn.image))
                        .resizable()
                        .scaledToFit()
                        .foregroundColor(Color(.blue))
                        .padding()
                        
                        
                }
            }
        }
    }

This is code code I've place in ContentView to call display the buttons in scrollview Using ForEach.

ScrollView(.vertical, showsIndicators: false)
                    {
                  ForEach(buttonsData) {
                item in
                        NavigationLink(destination: DetailView(buttons: item))
                    {
                            ButtonsDesignView(buttons: item)
                            .padding(10)
                            
                    }
        }.padding(.horizontal, 30)
        
            }

But with this code navigation link is not working.


Solution

  • You should add navigationLink to ButtonDesignView. I think that this should work;

    NavigationLink(destination: DetailView(buttons: buttons)) {
        Button(action: { }) {
               ZStack {
                   HStack{
                       VStack{
                   Text(btn.title)
                       .foregroundColor(Color(.blue))
                       .padding()
                   
                 Text(btn.subtitle)
                       .foregroundColor(Color(.blue))
                   .padding()
                       }
                       Spacer()
                       VStack{
                           Image(systemName: (btn.image))
                               .resizable()
                               .scaledToFit()
                               .foregroundColor(Color(.blue))
                               .padding()
                               
                               
                       }
                   }
               }
            }
        }