在 TableView 中搜索时 iOS 崩溃错误 indexPath 越界

标签 ios swift uitableview uisearchbar

我有 2 个数组,一个是 base 包含 532 个元素,另一个是 filter 数组。我有 UISearchBar 有委托(delegate)方法

func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
    self.filter(searchText: searchText)
}

private func filter(searchText: String) {
    if searchText.isEmpty {
        self.filterDelegates = self.delegates
    } else {
        self.filterDelegates = self.delegates.filter {
            $0.delegate.fullName.lowercased().contains(searchText.lowercased())
        }
    }
    self.tableView.reloadData()
}

当我滚动 tableview 并开始搜索时它崩溃了,它没有在 self.tableView.reloadData() 方法上重置 indexPath

在 indexpath 中登录 CellforRow

INDEXPATH : 23
FILTER COUNT : 396
INDEXPATH : 22
FILTER COUNT : 20


func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(
            withIdentifier: DelegateTableViewCell.defaultReuseIdentifier
        ) as! DelegateTableViewCell
        print("INDEXPATH : \(indexPath.row)")
        print("FILTER COUNT : \(self.filterDelegates.count)")
        cell.item = self.filterDelegates[indexPath.row] // Index out of bound
        return cell
    }

此外,我对 no 使用了相同的过滤器阵列。行法

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return self.filterDelegates.count
}

我做错了什么?

最佳答案

既然你是说当表格 View 滚动时会发生这种情况,我会像这样在搜索功能中停止滚动:

private func filter(searchText: String) {
    //force stop the scroll
    tableView.setContentOffset(tableView.contentOffset, animated: false) 

    if searchText.isEmpty {
        self.filterDelegates = self.delegates
    } else {
        self.filterDelegates = self.delegates.filter {
            $0.delegate.fullName.lowercased().contains(searchText.lowercased())
        }
    }
    self.tableView.reloadData()
}

关于在 TableView 中搜索时 iOS 崩溃错误 indexPath 越界,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51499979/

相关文章:

ios - 当我将 UITableView 添加到 subview 时,单元格不可选择

ios - UIImageView 开始动画不会对翻转图像进行动画处理

iOS - 从设备中获取所有照片并将它们保存到应用程序

ios - Viber、Telegram、WhatsApp 等 iOS 消息应用程序如何快速高效地获取联系人

ios - SwiftUI 中带循环的动态按钮

iOS 12 UIContextualAction 图像无法推断图像颜色

ios - 如何在自定义 UITableViewCell 中获取 UILabel 的字体大小?

ios - 如何从两个文本字段中获取值?

ios - 原型(prototype)单元格未显示在 UITableView 中

ios - UITableViewController 和背景颜色