我希望用户选择该城市的城市和地区。当我选择城市时,我想在选择器视图中列出该城市的地区。我还想在文本中显示城市的选择和地区的选择。
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[$0].city_name)
}
}.padding(.trailing, 50)
.id(UUID())
Picker(selection: $selectedFrameworkIndex, label: Text("")){
ForEach(0 ..< cityfetch.cities.count, id: \.self) {
Text(self.cityfetch.cities[$0].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 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 信息发布为图像。