我有我的數據庫中的字母節的tableview,我想添加搜索欄,但我無法弄清楚如何過濾數據並在tableview中實現它。 我的數據庫商店裏面有兩個結構體:搜索欄和使用swift3 tableview中的部分
一個結構體包含所有的數據。
第二個結構獲取部分的第一個字母和第一個結構作爲數組。
我的結構:
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
}
謝謝你的工作。爲什麼當我嘗試實現它到表視圖時,我得到錯誤(「致命錯誤:索引超出範圍」)代碼:('let filteredCrime:SentenceInfo = filteredData [indexPath.section] .crimes [indexPath.row]') –
確保根據* Note *中提到的搜索控制器的「isActive」,確定正確的值從'numberOfSections'和'numberOfRows'返回。 – vadian
你沒有注意到。工作得很好。謝謝你的幫助 –