我花了大约 3 个小时试图让这个 UISearchbar 工作。我有一个 Notes
的自定义类,它具有 .name
的属性。我正在尝试通过属性 .name
过滤数据(一组注释)。我已经实现了 delegate
并实例化了第二个过滤数组以及所有必需的协议(protocol)要求。但是,我似乎无法让我的搜索功能返回正确的数据。以下是我正在使用的当前代码。它构建良好,但是当我开始在搜索栏中键入内容时,出现了 index out range
错误,这发生在下面的行中并附有注释。这是在 View Controller 和其中的表 Controller 内完成的。
var notes = [Notes]()
var searchActive : Bool = false
var filtered = [Notes]()
/// these above vars are global ///
func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
searchActive = true;
}
func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {
searchActive = false;
}
func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
searchActive = false;
}
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
searchActive = false;
}
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
filtered = notes.filter(){ (Notes) -> Bool in
let range = Notes.name.range(of: searchText, options: NSString.CompareOptions.caseInsensitive)
return range != nil
}
if(filtered.count == 0){
searchActive = false;
} else {
searchActive = true;
}
self.tableView.reloadData()
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var note: Notes
if(searchActive){
//// THIS IS WHERE THE ERROR IS THROWN /////
note = filtered[indexPath.row]
} else {
note = notes[indexPath.row]
}
if let cell = tableView.dequeueReusableCell(withIdentifier: "NoteCell", for: indexPath as IndexPath) as? NoteCell {
cell.configureCell(note: note)
return cell
} else {
return NoteCell()
}
}
最佳答案
在 searchBarTextDidEndEditing
、searchBarCancelButtonClicked 方法中将
和 searchActive
设置为 false
后,尝试重新加载 tableView
searchBarSearchButtonClicked
。
注意: 不要在 searchBarTextDidBeginEditing
方法中将 searchActive
设置为 true
,因为如果您粘贴在搜索栏上并且没有输入任何内容并尝试滚动然后你也会得到索引越界崩溃。
编辑:检查 numberOfRowsInSection
是否正确实现。
func tableView(_ tableView:UITableView, numberOfRowsInSection section:Int) -> Int {
if searchActive {
return filtered.count
}
return notes.count
}
关于ios - UISearchBar iOS 返回索引超出范围的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41833916/