ios - 滚动并按搜索栏上的取消时应用程序崩溃

标签 ios swift uitableview

我的应用程序使用分页来显示表中的数据。每 5 个食谱,我都会向 Alamofire 发出一个新请求,以获取数据并将其显示在单元格中。我还有一个搜索栏,它使用相同的 tableView 来显示搜索到的数据(并且还使用分页)。

当我按下取消按钮时,将显示来自服务器的最新食谱。

问题是,如果我在两个“页面”之间滚动 并按下取消按钮,应用程序就会崩溃。

我的猜测是,发生这种情况是因为应用程序将尝试填充与搜索结果单元格对应的索引处的单元格(该索引将高于第一个列表的结果)。

搜索结果中的配方和主列表中的配方是相同的,因为它是一个模拟服务器(您可以查看控制台以更好地了解正在发出哪些请求)。 视频:https://www.youtube.com/watch?v=NGGZBZtY-J4&spfreload=10

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell") as! RecipeTableViewCell

    if searchController.isActive == false {
        cell.loadRecipePreview(recipe: recipes[indexPath.row])
        if indexPath.row == recipes.count - 1 {
            recipeRequest()
        }
    }
    else {
        cell.loadRecipePreview(recipe: searchRecipes[indexPath.row])
        if indexPath.row == searchRecipes.count - 1 {
            recipeSearchRequest()
        }
    }

    return cell
}

编辑:我认为这个问题与分页无关,因为当不在两个页面之间滚动时也会发生这种情况。

最佳答案

通过使用 if searchController.isActive == false && indexPath.row < recipes.count && recipes.count != 0 修改第一个 if 来修复尽管我不确定这是最好的方法。问题仍然悬而未决。

关于ios - 滚动并按搜索栏上的取消时应用程序崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43481162/

相关文章:

swift - 添加到 TableView 时 Realm 项会出现两次

iphone - Core Data : In what condition, 线程无法获取NSPersistentStoreCoordinator的锁?

swift - 如何更新从 array.count 获取值的标签?

ios - UIPageviewcontroller 滑动页面不工作

swift - UITableViewController 中的滑动操作没有出现在 swift 中

iphone - 自定义 UIITableViewCell 中的 UIImageView 在重新加载时不会切换

objective-c - 将节标题添加到 UITableView

ios - 无法使用 phonegap 打开 sqlite 数据库,但它在 objective-c 上运行良好

ios - 具有动态和静态单元格的 UICollectionView

ios - 如何控制 UIActivityIndi​​catorView 的旋转?