如何在tableview中搜索数据? [英] How to search data in tableview?
问题描述
我在本地文件中有数据,我已将它们加载到 tableView,现在我想通过搜索栏搜索/过滤.
I have data in local file, I have loaded them into the tableView, and now I want to search/filter via search bar.
我尝试了一些在 Internet 上找到的解决方案,但我不知道如何访问结构中的特定数据.
I have tried some solutions I've found on the Internet, but I don't know how to access specific data in my structure.
这是结构的一部分:
struct Model: Codable {
var data: [Description]
}
struct Description: Codable {
var id: Int
var name: String
var address: String
var city: String
var description: String
var countryId: Int
var webSite: String
var status: Int
var accountType: Int
var addDate: String
var placeGroupId: Int
var longitude: Double
var latitude: Double
var distance: Double
var working: Bool
var promotion: String
var repertoire: Repertoire
var workingHour: WorkingHour
var country: Country
var reviewNum: Int
var score: Double
var placeImgUrl: String
}
var model: Model?
这是我的 ViewController 中的一些代码:
and here is some code from my ViewController:
var filteredObjects = [Description]()
let searchController = UISearchController(searchResultsController: nil)
func searchBarIsEmpty() -> Bool {
return searchController.searchBar.text?.isEmpty ?? true
}
func filterContentForSearchText(_ searchText: String, scope: String = "All") {
}
extension ViewController: UISearchResultsUpdating {
func updateSearchResults(for searchController: UISearchController) {
<#code#>
}
}
我有变量模型,它是结构模型的类型.结构模型有一个变量数据,它是结构描述类型.最后,在结构描述中我有变量名.我的 tableView 单元格显示模型的名称 (model?.data[indexPathrow.row].name).现在,我需要按 tableView 单元格中显示的名称进行搜索.我希望我解释清楚.非常感谢!
I have variable model, which is type of struct Model. Structure Model have a variable data which is type of struct Description. And finally, in structure Description I have variable name. My tableView cells shows names of models (model?.data[indexPathrow.row].name). Now, I need to search by names shown in tableView cells. I hope I explained it clearly. Thank You very much!
推荐答案
假设 objects
也是 [Description]
并且表示数据源数组
Assuming objects
is also [Description]
and represents the data source array
func updateSearchResults(for searchController : UISearchController)
{
let searchString = searchController.searchBar.text!
if searchString.isEmpty {
filteredObjects.removeAll()
} else {
filteredObjects = objects.filter{ $0.name.range(of: searchString, options: .caseInsensitive) != nil }
}
tableView.reloadData()
}
在表视图数据源方法中显示 objects
或 filteredObjects
取决于 searchController.isActive
In the table view data source methods display objects
or filteredObjects
depending on searchController.isActive
这篇关于如何在tableview中搜索数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!