gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 16:26:49 26 4
gpt4 key购买 nike

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

为了将所选数量(UIStepper.value)从单元格发送回我的UITableViewController ,我已经实现了以下协议(protocol):

protocol UITableViewCellUpdateDelegate {
func cellDidChangeValue(cell: MenuItemTableViewCell)
}

这是我的自定义单元格中的 IBAction,其中 UIStepper 被 Hook :
@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({ $0.category == self.categories[indexPath.section] })
let item = itemsPerSection[indexPath.row]

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

在大多数情况下,上述设置运行良好。我不知道如何解决以下问题。这里有一个例子来说明:
  • 我设置了 UIStepper.value单元格 1 - 第 1 节,共 3 个。
  • 我向下滚动到表格 View 的底部,以便单元格 1 - 第 1 部分完全看不见。
  • 我设置了 UIStepper.value单元格 1 - 第 4 节,共 5 个。
  • 我向上滚动到顶部,以便单元格 1 - 第 1 部分重新出现在 View 中。
  • 我将 UIStepper 增加 1。所以数量应该是 4。相反,它是 6。

  • 调试整个事情表明这条线(在 UITableViewController 的委托(delegate)实现中)得到了错误的数量。看来 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({ $0.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)
    }
    .....
    ....
    ..
    .
    }

    最佳答案

    您需要更新 else 中的步进器值cellForRowAtIndexPath 中的子句:

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

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

    关于ios - self.tableView.indexPathForCell(cell) 返回错误的单元格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34827779/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com