ios - UISearchBar iOS 返回索引超出范围的错误

标签 ios swift3 uisearchbar

我花了大约 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()
    }

}

最佳答案

searchBarTextDidEndEditingsearchBarCancelButtonClicked 方法中将 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/

相关文章:

iphone - 移动到另一个 View Controller 时,UISearchBar 不会在 resignFirstResponder 上隐藏键盘

ios - 关于 leftBarButtonItem 没有以编程方式出现

ios - 在 Swift3 的 uiViewController 中添加广告横幅

ios - Swift 中带有 Unwind Segue 的 UITabBarController 不工作

swift - 试试!并尝试?有什么区别,什么时候使用它们?

swift - 在 Swift 中使用字符串变量的值引用对象

ipad - uisearchbar 未显示键盘

swift - 如何通过 UISearchBar 文本过滤掉内容?

iPhone:如何设置 UIViewController 框架?

ios - 如何在Objective-C中传递2个参数