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

Cascade pickers

Forums > SwiftUI

I'va got two arrays that have a common field. These arrays are used in pickers.

I'm trying to get to filter the second array based on the value from the first picker and use it in the second picker. Both are on the same view.

The issue i'm facing is that the second picked can't use the filtered array properly. It just hangs the view.

Any ideas ?

struct RegisterView: View {

    @State var regionId = 0
    @State var districtId = 0

    @State var filteredDistricts = []

        var body: some View {
        NavigationView{
        Form{
            Section{
                Picker(selection: $regionId, label: Text("Region")) {
                   ForEach(0 ..< regions.count) {
                    Text(regions[$0].ar)
                   }
                }.onReceive([self.regionId].publisher.first()) { value in
                    self.filteredDistricts = districts.filter( { return $0.regionId == regions[value].id })
                }
                if(regionId != 0){
                    Picker(selection: $districtId, label: Text("District")) {
                       ForEach(0 ..< filteredDistricts.count) {
                        Text(districts[$0].ar)
                       }
                    }
                }

            }
            Section{
                Button(action:{
                    print(self.filteredDistricts)
                }){
                    Text("print region value")
                }
            }
        }.navigationBarTitle("Registration")
        }

    }
}

2      

I added id: .self in the foreach loop but still nothing.

2      

@ihaze  

Try it ForEach(0 ..< regions.count) { Text(regions[$0].ar) }.id(regions[$0].regionID)

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.