【发布时间】:2016-01-16 13:56:44
【问题描述】:
我有一个带有自定义动态单元格的 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({ $0.category == self.categories[indexPath.section] })
let item = itemsPerSection[indexPath.row]
// get quantity from cell
item.quantity = cell.quantity
}
在大多数情况下,上述设置运行良好。我不知道如何解决以下问题。下面举个例子来说明:
- 我将单元格 1 - 部分 1 的
UIStepper.value设置为 3。 - 我向下滚动到表格视图的底部,以使单元格 1 - 部分 1 完全看不见。
- 我将单元格 1 - 第 4 节的
UIStepper.value设置为 5。 - 我向上滚动到顶部,以便单元格 1 - 部分 1 重新出现在视图中。
- 我将 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({ $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)
}
.....
....
..
.
}
【问题讨论】:
标签: ios uitableview swift2 uistoryboard