0

I'm trying to but a NavigationLink in a LazyVGrid and I'm having a bit of trouble with the navigation. I would like that when the color is clicked that I could segue to the next page. Here is some code:

Here is how the start page looks here

Here is how the image card is set up:

 ZStack{ Color(colorData.image) .cornerRadius(15) .aspectRatio(contentMode: .fit) .padding(8) .matchedGeometryEffect(id: colorData.image, in: animation) } 

Here is how the LazyVgrid is set up:

 ScrollView(.vertical, showsIndicators: false, content: { VStack{ LazyVGrid(columns: Array(repeating: GridItem(.flexible(),spacing: 15), count: 2),spacing: 15){ ForEach(bags){color in ColorView(colorData: color,animation: animation) .onTapGesture { withAnimation(.easeIn){ print("pressed") selectedColor = color } } } } .padding() .padding(.top,10) } }) } 

Here is how I navigate:

 if selectedColor != nil { NavigationLink(destination: DetailView()) {} } 
1
  • 1
    could you show some more code? Where is selectBag defined? You could also try just wrapping the ColorView in a NavigationLink to DetailView. Commented Jul 30, 2021 at 13:41

2 Answers 2

1

You can do as mentioned in @workingdog's answer, or slightly modify the code like so:

struct ContentView: View { @State var isActive: Bool = false @State var selectedColor: Color? var body: some View { NavigationView { NavigationLink(destination: DetailsVieww(selectedColor: selectedColor), isActive: $isActive) { EmptyView() } VStack { ColorView(colorData: color, animation: animation) .onTapGesture { selectedColor = color isActive = true } } } } } 
Sign up to request clarification or add additional context in comments.

Comments

0

typically with navigation you would do something like this:

struct ContentView: View { @State var selection: Int? @State var selectedColor: Color? var body: some View { NavigationView { // <--- required somewhere in the hierarchy of views // .... NavigationLink(destination: DetailsVieww(selectedColor: selectedColor), tag: 1, selection: $selection) { ColorView(colorData: color, animation: animation) .onTapGesture { withAnimation(.easeIn) { selectedColor = color selection = 1 // <--- will trigger just the tag=1 NavigationLink } } } // .... } } } struct DetailsVieww: View { @State var selectedColor: Color? var body: some View { Text("selected color view \(selectedColor?.description ?? "")") } } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.