self.tableView.indexPathForCell(cell) 返回错误的单元格?

self.tableView.indexPathForCell(cell) returning wrong cell?

我有一个带有自定义动态单元格的 UITableView(多个部分)。每个单元格都有一个代表所选数量的 UIStepper。

为了将选定的数量 (UIStepper.value) 从单元发送回我的 UITableViewController,我实施了以下协议:

protocol UITableViewCellUpdateDelegate {
    func cellDidChangeValue(cell: MenuItemTableViewCell)
}

这是我的自定义单元格中的 IBAction,其中 UIStepper 已挂钩:

@IBAction func PressStepper(sender: UIStepper) {

    quantity = Int(cellQuantityStepper.value)

    cellQuantity.text = "\(quantity)"

    self.delegate?.cellDidChangeValue(self)
}

在我的 UITableViewController 中,我通过以下方式捕获它:

func cellDidChangeValue(cell: MenuItemTableViewCell) {

    guard let indexPath = self.tableView.indexPathForCell(cell) else {
        return
    }

    // Update data source - we have cell and its indexPath
    let itemsPerSection = items.filter({ [=13=].category == self.categories[indexPath.section] })
    let item = itemsPerSection[indexPath.row]

    // get quantity from cell
    item.quantity = cell.quantity        
}

在大多数情况下,上述设置效果很好。我不知道如何解决以下问题。下面举个例子来说明:

  1. 我将单元格 1 - 第 1 部分的 UIStepper.value 设置为 3。
  2. 我向下滚动到 table 视图的底部,以便单元格 1 - 第 1 部分完全不在视图中。
  3. 我将单元格 1 - 第 4 部分的 UIStepper.value 设置为 5。
  4. 我向上滚动到顶部,以便单元格 1 - 第 1 部分重新出现在视图中。
  5. 我将 UIStepper 增加 1。所以数量应该是 4。相反,它是 6。

调试整个事情表明这一行(在 UITableViewController 的委托实现中)得到了错误的数量。似乎 indexPathForCell 获取了错误的单元格,因此返回了错误的数量?

// cell.quantity is wrong
item.quantity = cell.quantity

为了完整起见,这里是 cellForRowAtIndexPath 实现,其中单元格在进入视图时被出队:

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    let cellIdentifier = "MenuItemTableViewCell"

    let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! MenuItemTableViewCell

    cell.delegate = self

    // Match category (section) with items from data source
    let itemsPerSection = items.filter({ [=15=].category == self.categories[indexPath.section] })
    let item = itemsPerSection[indexPath.row]

    // cell data
    cell.cellTitle.text = item.name + "  " + formatter.stringFromNumber(item.price)!
    cell.cellDescription.text = item.description
    cell.cellPrice.text = String(item.price)

    if item.setZeroQuantity == true {
        item.quantity = 0
        cell.cellQuantityStepper.value = 0
        cell.cellQuantity.text = String(item.quantity)

        // reset for next time
        item.setZeroQuantity = false
    }
    else {
        cell.cellQuantity.text = String(item.quantity)
    }
    .....
    ....
    ..
    .
}

您需要更新 cellForRowAtIndexPathelse 子句中的步进值:

else {
    cell.cellQuantity.text = String(item.quantity)
    cell.cellQuantityStepper.value = Double(item.quantity)
}

否则步进器会保留上次使用单元格时的值。