UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

SOLVED: Select value of array and pass it to another view by NavigationLink

Forums > SwiftUI

I have a view with an array:

@State private var categoria = [
        "Acessórios para Veículos",
        "Agro",
        "Alimentos e Bebidas",
        "Animais",

and a foreach loop

   ForEach(categoria, id: \.self) { categoria in
                        NavigationLink(destination: Destino(categoria: self.$categoria)) {
                            Text(categoria)
                        }

in other view (Destino) i want to receive the categoria of selected by user.

i try @Binding var categoria: [String]

 ForEach(viewModel2.anuncios.filter({ "\($0)".contains(categoria[0]) })) { anuncio in
                ClassRowView(anuncio:anuncio)
            }

But i neet to use [0] and i dont have the exact array that the user selected. Can u help me? how i can pass the correct value in contains(categoria) ?

Thanks!!

2      

Think you are get confused with your namings

Your array is

@State private var categories = [
        "Acessórios para Veículos",
        "Agro",
        "Alimentos e Bebidas",
        "Animais",
]

So when you create the ForEach in the view

ForEach(categories, id: \.self) { category in // <- this line select one from the array above
  NavigationLink(destination: DestinoView(category: category)) {  // <- this pass the selected string from array
      Text(category) // <- this display the selected string from array
  }
}

so in the DestinoView you just need

let category: String

if you want to pass the whole array to the DestinoView then you do not need the ForEach put let categories: [String] in it and then you can do ForEach in this view.

You use @Binding when you want to pass back the the orginal view.

@Binding var categories: [String]

and in the orginal view have

NavigationLink(destination: DestinoView(categories: $categories)) {
    Text("Next View")
}

Hope that is clear because I was not sure what you were trying to get!

3      

I Love you thanks!

2      

TAKE YOUR SKILLS TO THE NEXT LEVEL If you like Hacking with Swift, you'll love Hacking with Swift+ – it's my premium service where you can learn advanced Swift and SwiftUI, functional programming, algorithms, and more. Plus it comes with stacks of benefits, including monthly live streams, downloadable projects, a 20% discount on all books, and free gifts!

Find out more

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.