我的场景,我创建了UITableView
具有以下结构 JSON
数据加载。我需要添加global
搜索 firstname
, price
, date
, title
和 description
。在这里,我尝试过,但对我来说效果不佳。请给我一些解决方案。
例如:用户 searched
通过name
或price
, date
, title
和 description
UITableView 应该整理列表。
我的可编码结构
struct Welcome: Codable {
let status: Int
let message: String
let ode: Int
let data: [Datum]
}
struct Datum: Codable {
let id: Int
let title, description: String
let price: Int
let user: User
let Appcode: Appcode
let Appbase: Appbase
enum CodingKeys: String, CodingKey {
case id
case userID = "userid"
case title, description
case price
case Date = "date"
case location, user
case appcode = "appcode”
case appbase = "appbase”
}
}
struct Appcode: Codable {
let card: String
}
struct Appbase: Codable {
let base: String
}
struct User: Codable {
let firstname, lastname: String
}
我的Tableview代码
var tableArray = [Datum]()
var filteredResults = [Datum]()
lazy var searchBar:UISearchBar = UISearchBar()
var isSearching = false
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if isSearching {
return filteredResults.count
} else {
return self.tableArray.count
}
return 0
}
我的搜索条码
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
if searchBar.text == nil || searchBar.text == "" { //
isSearching = false
view.endEditing(true)
tableView.reloadData()
}
else {
isSearching = true
filteredResults = tableArray.filter({ value -> Bool in
guard let text = searchBar.text else { return false}
return value.description.contains(text) // According to title from JSON
})
tableView.reloadData()
}
}
最佳答案
在您的结构数据中,您的 CodingKeys 与您的属性名称不匹配
The names of the enumeration cases should match the names you've given to the corresponding properties in your type.
如果您像这样更新结构:
struct Datum: Codable {
let id: Int
let title, description: String
let price: Int
let user: User
let appCode: Appcode
let appBase: Appbase
enum CodingKeys: String, CodingKey {
case id
case title, description
case price
case user
case appCode = "appcode"
case appBase = "appbase"
}
}
您可以稍后像这样过滤元素数组:
let datum1 = Datum(id: 1, title: "test", description: "test1", price: 10, user: User(firstname: "a", lastname: "b"), appCode: Appcode(card: "app"), appBase: Appbase(base: "base"))
let datum2 = Datum(id: 1, title: "test", description: "test2", price: 10, user: User(firstname: "a", lastname: "b"), appCode: Appcode(card: "app"), appBase: Appbase(base: "base"))
let datum3 = Datum(id: 1, title: "test", description: "test3", price: 10, user: User(firstname: "a", lastname: "b"), appCode: Appcode(card: "app"), appBase: Appbase(base: "base"))
let array = [datum1, datum2, datum3]
array.filter{$0.user.firstname == "a"}
array.filter{$0.description.contains("2")}
关于ios - 如何使用 Swift 4.2 在 TableView 中创建 JSON 可编码结构数据的搜索功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54793387/