首页 > 解决方案 > 删除 UITableViewRow 时出错,单击的行索引不在可能的索引范围内

问题描述

我在使用自定义按钮手动删除项目时遇到问题,当用户单击该变量的值处的减号 == 1 时,项目的数量(单元格的变量)会发生。单元格正确地向上滑动为前一个被删除,但是当下面的所有单元格上升时,索引不会改变,即使我正确地从字典中删除了单元格和值。

我试图无法在屏幕上进行用户活动,但这仍然不是问题,因为我知道这是类型索引超出范围错误。

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

    ordersTableView.register(UINib(nibName: "OrdersTableViewCell", bundle: .main), forCellReuseIdentifier: "ordersTableViewCell")

    let cell = ordersTableView.dequeueReusableCell(withIdentifier: "ordersTableViewCell", for: indexPath) as! OrdersTableViewCell
    let amount = dishesDictionary[indexPath.item]![4] as! Int 
    cell.dishAmountLabel.text = ("\(String(amount))x")



@objc func decreaseAmount(sender: UIButton){



    let index = sender.tag
    let indexPath = IndexPath(item: index, section: 0)

    if (dishesDictionary[index]![4] as! Int) > 1 {

        let numberOfItems = dishesDictionary[index]![4] as! Int
        dishesDictionary[index]![4] = numberOfItems - 1


        ordersTableView.reloadRows(at: [indexPath], with: .fade)
        print(dishesDictionary[index])
        print("COUNT: \(dishesDictionary.count)")
    }

    else if (dishesDictionary[index]![4] as! Int) == 1 {

        ordersTableView.beginUpdates()
        self.dishesDictionary.removeValue(forKey: index)
        self.ordersTableView.deleteRows(at: [indexPath], with: .fade)
        ordersTableView.endUpdates()
        UIApplication.shared.beginIgnoringInteractionEvents()
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.7, execute: {
            self.ordersTableView.reloadData()
            UIApplication.shared.endIgnoringInteractionEvents()
        })

    }

    else {
        return
    }
    calculateTotalAmount()
}

标签: swiftuitableviewoptional

解决方案


推荐阅读