我花了大约3个小时来尝试使该UISearchbar正常工作。我有一个Notes
的自定义类,它的一个属性是.name
。我正在尝试通过属性.name
过滤数据(注释数组)。我已经实现了delegate
并实例化了第二个过滤后的数组以及所有必需的协议要求。但是,我似乎无法获得搜索功能来返回正确的数据。下面是我正在使用的当前代码。它构建良好,但是当我开始在搜索栏中键入内容时,出现错误index out range
,这发生在下面带有注释的行中。这是从内部的视图控制器和表控制器中完成的。
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()
}
}
最佳答案
在方法tableView
,searchActive
和false
中将searchBarTextDidEndEditing
设置为searchBarCancelButtonClicked
之后,也尝试重新加载searchBarSearchButtonClicked
。
注意:请勿在方法searchActive
中将true
设置为searchBarTextDidBeginEditing
,因为如果您用胶带贴在Searbar上并且没有键入任何内容并尝试滚动,那么索引也会超出范围崩溃。
编辑:检查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/