Search code examples
swiftuiscrollviewswiftui-navigationlinklazyvgrid

How can implement a navigationLink inside of a LazyVGrid and ForEach statement?


How can I implement play buttons that navigate to different views in the corner of each music category item? Here is an image of what I am looking for:

What I am looking for

Here is my code:

struct ScrollCategories: View {
    
    var body: some View {
        ZStack {
            ScrollView {
                LazyVGrid (columns: [GridItem(.fixed(200)), GridItem(.fixed(200))]) {
                    ForEach(musics) { sub in
                        ZStack {
                            VStack(alignment: .leading) {
                                //Hidden Code
                            } // END OF VSTACK
                            NavigationLink {
                                // Naviagte to a different view!
                                Onboarding()
                            } label: {
                                Image(systemName: "play.circle")
                                    .font(.system(size: 30))
                                    .padding(.leading, -72.0)
                                    .padding(.bottom, 130.0)
                            }
                        } // END OF ZSTACK
                    }// END OF FOR EACH
                } // END OF GRID ITEM
            } // END OF SCROLL VIEW
        } //END OF ZSTACK
    }
}

As you can see, I have a navigation link, yet it does not show in the preview or simulator.

Here is an image of what the preview looks like: What the XCode preview looks like


Solution

  • Your navigation link is there. You just use padding too high that it was out of the frame. You can use ZStack with alignment to put on the left-top corner and add padding to make it nice.

    ZStack(alignment: .topLeading) { <- positioning for each View
        VStack(alignment: .leading) {
            //Hidden Code
        } // END OF VSTACK// END OF VSTACk
    
        NavigationLink {
            // Navigate to a different view!
            Onboarding()
        } label: {
            Image(systemName: "play.circle")
                .font(.system(size: 30)) 
                .padding( {{ put your desire padding }}) 
        }
    } // END OF ZSTACK
    

    enter image description here