我的数据库中有带有字母部分的表格 View ,我想添加搜索栏,但我不知道如何过滤数据并在表格 View 中实现它。
我的数据库存储在两个结构中:
一个包含所有数据的结构。
第二个结构获取部分的第一个字母,第一个结构作为数组。
我的结构:
struct SentenceInfo { // First struct (holds all the data)
let name: String
let detail: String
let sentence: String
init(name: String, detail: String, sentence: String) {
self.name = name
self.detail = detail
self.sentence = sentence
}
}
struct SentenceNameSection { // Second struct (first letter and array of the first struct)
var firstLetter: String
var crimes: [SentenceInfo]
init(title: String, objects: [SentenceInfo]) {
firstLetter = title
crimes = objects
}
}
我的 TableView :
var sections : [SentenceNameSection]!
var crimeData = [SentenceNameSection]()
var filteredData = [SentenceNameSection]()
var shouldShowSearchResults = false
var searchController: UISearchController!
func updateSearchResults(for searchController: UISearchController) {
let searchString = searchController.searchBar.text
filteredData = crimeData.filter({ (crime) -> Bool in
let crimeMatch: String = crime // Error about types
return ((crimeMatch.range(of: searchString!) != nil))
})
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell: sentenceTableViewCell = tableView.dequeueReusableCell(withIdentifier: cellIdentifer, for: indexPath) as! sentenceTableViewCell
let crime: SentenceInfo = sections[indexPath.section].crimes[indexPath.row]
cell.nameLabel.text = crime.name
cell.detailLabel.text = crime.detail
cell.sentenceLabel.text = crime.sentence
return cell
}
最佳答案
首先crimeData
包含 SentenceNameSection
无法与 String
相比
除此之外,要过滤包含部分的数据源数组,您必须使用重复循环并创建新的 SentenceNameSection
项目
此代码搜索 SentenceInfo
中的所有三个属性。结构
let searchString = searchController.searchBar.text!
filteredData.removeAll() // is mandatory to empty the filtered array
for section in crimeData {
let filteredContent = section.crimes.filter { $0.name.range(of: searchString) != nil
|| $0.detail.range(of: searchString) != nil
|| $0.sentence.range(of: searchString) != nil
}
if !filteredContent.isEmpty {
filteredData.append(SentenceNameSection(title: section.firstLetter, objects: filteredContent))
}
}
注:当然你必须处理
search
所有适当的 TableView 数据源和委托(delegate)方法中的大小写。
关于uitableview - 使用swift3在tableview中搜索栏和部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40817577/