如何在 Swift UI 中将嵌套的 JSON 值显示到选取器视图中?

How to show Nested JSON values into the pickerview in Swift UI?

我希望用户select那个城市的城市和地区。当我 select 城市时,我想在 pickerview 中列出该城市的地区。我还想在文本中显示城市的 selection 和地区的 selection。

struct locationView: View {


@State var selectedFrameworkIndex = 0
@State var tap1 : Bool = false

@ObservedObject var cityfetch = cityFetcher()

var selectedCityName: String? {
    if !cityfetch.cities.isEmpty && selectedFrameworkIndex < cityfetch.cities.count {
        return cityfetch.cities[selectedFrameworkIndex].city_name
    } else {
        return nil
    }
}

var body: some View {
    
          
            VStack{
                
                
                Picker(selection: $selectedFrameworkIndex, label: Text("")) {
                    ForEach(0 ..< cityfetch.cities.count, id: \.self) {
                        
                        Text(self.cityfetch.cities[[=13=]].city_name)
                    }
                }.padding(.trailing, 50)
                    .id(UUID())
                
                
                Picker(selection: $selectedFrameworkIndex, label: Text("")){
                    ForEach(0 ..< cityfetch.cities.count, id: \.self) {
                        
                        Text(self.cityfetch.cities[[=13=]].district_name)
                    }
                }.padding(.trailing, 50)
                    .id(UUID())
                
            }
            
            
            
            Text("Seçiminiz: \(selectedCityName ?? "")")
                .font(.system(size: 20, weight: .regular, design: .rounded))
            
            
        }

struct city : Decodable, Identifiable{

let id = UUID()
let city_id : Int
let city_name : String
let district_id : Int
let district_name : String
}

我的 class 正在关注..

class cityFetcher : ObservableObject{

@Published var cities = [city]()


init() {
    loadCity()
    
}
func loadCity(){
    
    let url = URL(string: "https://raw.githubusercontent.com/midorikocak/turkish-cities-districts/master/data/il-ilce.json")
    URLSession.shared.dataTask(with: url!) { (data, response, error) in
        do{
            let cities = try JSONDecoder().decode([city].self, from: data!)
            DispatchQueue.main.async {
                self.cities = cities
                
            }
                
            
        }   catch{
            print("Error")
        }
    }.resume()
    
    
}

}

我还将我的 JSON 信息作为图片发布。

cityFetcher中添加函数getUniqiueCities()创建一个独特的城市数组,并在self.cities = cities之后调用此函数。在 cityFetcher.

中创建 @Published var uniqueCities : [city] = []
func getUniqiueCities() {
        var uniqueCities: [city] = []
        for city in self.cities {
            let isExists =  uniqueCities.contains{ item in
                return item.city_name == city.city_name
            }
            if !isExists {
              uniqueCities.append(city)
            }
        }
        self.uniqueCities =  uniqueCities
    }

运行 unique cities 的循环并根据唯一的城市名称显示地区。 使用以下代码

更新 LocationView
struct locationView: View {
    @State var selectedFrameworkIndex = 0
    @State var selectedCityIndex = 0
    @State var tap1 : Bool = false
    @ObservedObject var cityfetch = cityFetcher()

    var selectedCityName: String? {
        if !self.cityfetch.uniqueCities.isEmpty && selectedFrameworkIndex < self.cityfetch.uniqueCities.count {
            return self.cityfetch.uniqueCities[selectedFrameworkIndex].city_name
        } else {
            return nil
        }
    }

    var body: some View {
        VStack{
            Picker(selection: $selectedFrameworkIndex, label: Text("")) {
                ForEach(0 ..< self.cityfetch.uniqueCities.count, id: \.self) {
                    Text(self.cityfetch.uniqueCities[[=11=]].city_name)
                }
            }.padding(.trailing, 50)
            .id(UUID())
            Picker(selection: $selectedCityIndex, label: Text("")){
                ForEach(0 ..< self.getFilteredDistricts().count, id: \.self) {
                    Text(self.getFilteredDistricts()[[=11=]].district_name)
                }
            }.padding(.trailing, 50)
            .id(UUID())
            
        
                  
        Text("Seçiminiz: \(selectedCityName ?? "")")
            .font(.system(size: 20, weight: .regular, design: .rounded))
        }
    }
    
    func getFilteredDistricts() -> [city] {
        return self.cityfetch.cities.filter({[=11=].city_name == self.cityfetch.uniqueCities[selectedFrameworkIndex].city_name})
    }
    
}

更新

根据评论,添加代码以获取 selectedDistrict:

var selectedDistrict: String? {
        if !self.getFilteredDistricts().isEmpty && selectedCityIndex < self.getFilteredDistricts().count {
            return self.getFilteredDistricts()[selectedCityIndex].district_name
        } else {
            return nil
        }
    }