我遇到的情况是,我有点卡住了。简单来说,我的任务是将JSON解析为(例如)UITableView,并通过本地SearchBar进行过滤。
JSON看起来像这样。
{
"title":"Two",
"image":"Two.png"
}
...等等
经过解析后,我得到了一个字典阵列,它的样子是这样的(分解后可以有更深的了解
imagesArray = [["title":"Two", "image":"Two.png"],["title":"Three Four", "image":"ThreeFour.png"],["title":"Five", "image":"Five.png"]]
我必须使用 "title "名称进行过滤.虽然,我真的不知道如何使用native SearchBar通过Dicts数组进行过滤,但我知道有一些方法。
如果我对Dicts数组的整体概念是错误的,请随时纠正我,并展示任何不同的方法:()
谢谢!我的情况是
你可以将JSON解析成一个dicts数组,然而,我建议将数据解析成一个可编码结构或类的数组,就像这样。
let json = """
[
{
"title":"Two",
"image":"Two.png"
}
]
"""
struct Item: Codable {
var title, image: String
}
if let jsonData = json.data(using: .utf8) {
do {
var items = try JSONDecoder().decode([Item].self, from: jsonData)
} catch {
print("Error: " + error.localizedDescription)
}
}
class del: NSObject,UISearchBarDelegate {
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
}
}
一旦你有了对象数组,你就可以把它们过滤成一个新的数组,在textDidChange UISearchBarDelegate方法中作为UITableView的数据,像这样。
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
let filteredItems = items.filter { (item) in
item.title
.lowercased()
.contains(searchText.lowercased())
}
}
希望这能帮到你。
func searchFor(_ chars: String) -> [[String : String]] {
return imagesArray.filter { ($0["title"]?.range(of: chars, options: .caseInsensitive) != nil) }
}
print(searchFor("th")) // [["title": "Three Four", "image": "ThreeFour.png"]]