ios - TableView中SearchController过滤问题
问题描述
我有下一个模型:
struct HashTags {
var title = ""
var tags = [String]()
}
我尝试使用 UISearchController 在标签数组中搜索文本。
我在 TableViewController 中实现了 UISearchController:
class TagsController: UITableViewController {
var hashtags = [HashTags]()
var filtered = [HashTags]()
let searchController = UISearchController(searchResultsController: nil)
var searchBarIsEmpty: Bool {
guard let text = searchController.searchBar.text else { return false }
return text.isEmpty
}
var isFiltering: Bool {
return searchController.isActive && !searchBarIsEmpty
}
override func viewDidLoad() {
super.viewDidLoad()
searchController.searchResultsUpdater = self
searchController.obscuresBackgroundDuringPresentation = false
searchController.searchBar.placeholder = "Search"
navigationItem.searchController = searchController
definesPresentationContext = true
}
override func numberOfSections(in tableView: UITableView) -> Int {
if isFiltering {
return filtered.count
}
return hashtags.count
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
if isFiltering {
return filtered[section].title
}
return hashtags[section].title
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if isFiltering {
return filtered[section].tags.count
}
return 1
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Tags", for: indexPath)
var item = HashTags()
if isFiltering {
item = filtered[indexPath.section]
} else {
item = hashtags[indexPath.section]
}
let tags = item.tags
cell.textLabel?.text = tags.joined(separator: ", ")
return cell
}
}
extension TagsController: UISearchResultsUpdating {
func updateSearchResults(for searchController: UISearchController) {
filterContentForSearchText(searchController.searchBar.text!)
}
func filterContentForSearchText(_ searchText: String) {
filtered = hashtags.filter({ (hashtag: HashTags) -> Bool in
return hashtag.tags.contains(searchText.lowercased())
})
tableView.reloadData()
}
}
但它不能正常工作,当我开始输入文本时,我会收到空白屏幕。我需要 UISearchController 正常工作并在 HashTags 标签数组中搜索文本,显示正确的部分和行数。
解决方案
推荐阅读
- reactjs - DOM to Canvas 如何获取要渲染的图像
- bootstrap-modal - 从引导程序的模态形式发布数据:我错过了什么?
- kentico - Kentico 在 Widget 或 Webpart 中重命名“代号”而不丢失数据
- javascript - 防止函数onkeydown javascript
- laravel - 使用 SweetAlert、Vue 和 Laravel 进行确认
- xml - 我如何更新
根据给定的文件名在我的 XML 中 - php - PHP - 在每个新创建的数组中 foreach 重复值
- powerbi - Power BI DAX 中的条件划分
- excel - 单元格中的值范围
- python-2.7 - 如何分组列以将数据保留在新数据框中并使用 Python 2.7 在 pandas 中按日期时间排序