我正在构建一个旅行计划应用程序,允许用户使用 Picker 从本地 json 文件中选择一个城市。
json 文件有 115K 项目,如果我尝试过滤这么多项目,UI 会冻结。关于如何提高效率的任何建议。
任何帮助将不胜感激。
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"
}]