0

我正在构建一个旅行计划应用程序,让用户从本地 json 文件中选择一个城市。

我可以显示和过滤列表(使用选择器),但我不知道如何读取和存储选择。

任何帮助将不胜感激。

模型

import Foundation

struct Destination: Codable, Hashable, Identifiable {
    
    var id: Int
    let city: String
    let country: String
    
}

选择器视图

import SwiftUI

struct AddTripView: View {

    let cities = Bundle.main.decode([Destination].self, from: "cities.json")
    @State private var selectedCity = 0
    @State var searchText = ""

       var body: some View {
        
            Form {
                Section {
                    Picker(selection: $selectedCity, label: Text("Select city")) {
                        
                        SearchBar(text: $searchText)
 
                        ForEach(cities.filter {searchText.isEmpty ? true : $0.city.lowercased().hasPrefix(searchText.lowercased())}, id: \.self) {
                            
                            Text($0.city)
                        }
                    }
                }
            }.navigationBarTitle("Create trip")
            
        }
}

struct AddTripView_Previews: PreviewProvider {
    static var previews: some View {
        AddTripView()
    }
}

JSON 示例

[{
    "id": 1,
    "city": "Zaranj",
    "country": "Afghanistan"
  },
  {
    "id": 2,
    "city": "Taloqan",
    "country": "Afghanistan"
  },
  {
    "id": 3,
    "city": "Shīnḏanḏ",
    "country": "Afghanistan"
  },
  {
    "id": 4,
    "city": "Shibirghān",
    "country": "Afghanistan"
  },
  {
    "id": 5,
    "city": "Shahrak",
    "country": "Afghanistan"
  }]
4

0 回答 0