Arrays 如何附加/使用UISearchBar在swift中搜索时找到的匹配值?
正如你在我的代码中看到的,我有嵌套的数组/字典,我必须在不同的键中一起进行搜索,就像student_name,student_name在student Dictionary中一样,一切都很好,但我在这里面临的唯一问题是,无论搜索栏找到什么,我都必须在单元格中显示,但由于嵌套的字典,我不知道如何在单元格中显示Arrays 如何附加/使用UISearchBar在swift中搜索时找到的匹配值?,arrays,uitableview,dictionary,uisearchbar,swift5,Arrays,Uitableview,Dictionary,Uisearchbar,Swift5,正如你在我的代码中看到的,我有嵌套的数组/字典,我必须在不同的键中一起进行搜索,就像student_name,student_name在student Dictionary中一样,一切都很好,但我在这里面临的唯一问题是,无论搜索栏找到什么,我都必须在单元格中显示,但由于嵌套的字典,我不知道如何在单元格中显示 cell.nameLbl.text = (What should I write here to show found values???) 若我必须再创建一个数组来附加searchBa
cell.nameLbl.text = (What should I write here to show found values???)
若我必须再创建一个数组来附加searchBar找到的值,那个么问题是我应该在代码中写什么,我要附加什么
var foundName:[String] = [] (Declared global variable to save only string that already matched)
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
filteredData = schoolData.filter{(item:School?) -> Bool in
return ((item?.resultMap["teacher"] as? String)?.range(of: searchText, options: .caseInsensitive, range: nil, locale: nil) != nil) ||
((item?.resultMap["class"] as? String)?.range(of: searchText, options: .caseInsensitive, range: nil, locale: nil) != nil) ||
((((item?.resultMap["student"]) as? [String: Any?])?["student_name"] as? String)?.range(of: searchText, options: .caseInsensitive, range: nil, locale: nil) != nil)
}
foundName.append(contentsOf: (what should I write here .. ))
tableView.reloadData()
}
}您必须创建一个包含搜索值的数组。应在func搜索栏中填充此数组 cell.nameLbl.text=我应该在这里写什么来显示找到的值 修改search func以填充找到的值,并使用map仅返回作为字符串数组搜索的任何字段的结果。我在下面提供了一个示例,说明如何将schoolData对象转换为返回学校名称数组
func searchBar(_ searchBar: UISearchBar? = nil, textDidChange searchText: String) {
let filteredData = schoolData.filter { item in
return (item.name?.range(of: searchText, options: .caseInsensitive, range: nil, locale: nil) != nil)
}
foundNames = filteredData.map({
($0.name ?? "")
})
}
这是我使用的示例数据
var schoolData: [School] = [School(id: 1, name: "First"),
School(id: 2, name: "Second"),
School(id: 3, name: "Third"),
School(id: 4, name: "Four")]
class School {
var id: Int?
var name: String?
init(id: Int, name: String) {
self.id = id
self.name = name
}
}
如果您有任何问题,请告诉我。这是我问题的答案,我终于找到了答案
if let title = item?.resultMap["teacher"] as? String, title.prefix(2) == searchText {
self.foundName.append(item?.resultMap["teacher"] as? String ?? "")
}
对于cell这是我写的代码
cell.nameLbl.text = foundName[indexPath.row]
谢谢你的评论,但这不是我想要的答案,这是我在搜索时必须使用的json:老师、班级、学生的名字。Json是{研究:{学校:[{学校名称:纽约学校,教师:Micheal,班级:标准第一,学生:{学生名称:David},学校时间:{开始时间:2020年3月13日}]}}我在项目中遇到错误。结果图。给我发送代码,将json转换为您在searchBar func中使用的对象。我添加了答案,请检查。
cell.nameLbl.text = foundName[indexPath.row]