I have a view where there are 2 square cells in each row, and I get my data from an API ( album image and name), in each cell there is an image and the image name below it. I'm using NavigationLink to lead to details about the cell. The default behavior for NavigationLink is to tap the whole row so both of my images detail pages open right after each other. Since I'm using forEach loop to traverse my array that contains image links and other data I can't use indexes to specify which NavigationView is which. How do I make it so that each cell is tappable an leads to its details View?
I used a method called chunked to display 2 cells (views in a NavigationLink). Visually it is correct but the tapping behavior is stated as above.
'''
extension Array{
func chunked(into size: Int) -> [[Element]]{
return stride(from: 0, to:count, by: size).map {
Array(self[$0 ..< Swift.min($0 + size, count)])
}
}
}
'''
code for the contentView:
struct ContentView: View {
@StateObject private var gVM = GenreViewModel()
var body: some View {
NavigationStack{
ZStack{
ScrollView{
ForEach(gVM.genres.chunked(into: 2), id:\.self) { chunk in
ForEach(chunk, id: \.name) { genre in
Button {
NavigationLink(destination: Text("hello")){
GenreView(genre: genre)
}
} label: {
GenreView(genre: genre)
}
}
}
}
}.listStyle(.plain).navigationBarTitle("Categories", displayMode: .inline)
.alert(isPresented: $gVM.hasError, error: gVM.error){
Button(action: gVM.fetchGenres){
Text("try again")
}
}
}.onAppear(perform: gVM.fetchGenres)
}
}
}