ios - self.tableView.indexPathForCell(cell) returning wrong cell? -
i have uitableview (multiple sections) custom dynamic cells. each cell has uistepper representing selected quantity.
in order send selected quantity (uistepper.value) cell uitableviewcontroller, have implemented following protocol:
protocol uitableviewcellupdatedelegate { func celldidchangevalue(cell: menuitemtableviewcell) } and ibaction in custom cell uistepper hooked:
@ibaction func pressstepper(sender: uistepper) { quantity = int(cellquantitystepper.value) cellquantity.text = "\(quantity)" self.delegate?.celldidchangevalue(self) } and within uitableviewcontroller capture via:
func celldidchangevalue(cell: menuitemtableviewcell) { guard let indexpath = self.tableview.indexpathforcell(cell) else { return } // update data source - have cell , indexpath let itemspersection = items.filter({ $0.category == self.categories[indexpath.section] }) let item = itemspersection[indexpath.row] // quantity cell item.quantity = cell.quantity } the above setup works well, cases. can't figure out how solve following problem. here's example illustrate:
- i set
uistepper.valueof 3 cell 1 - section 1. - i scroll down bottom of table view cell 1 - section 1 out of view.
- i set
uistepper.valueof 5 cell 1 - section 4. - i scroll top of cell 1 - section 1 view.
- i increase uistepper 1. quantity should have been 4. instead, it's 6.
debugging whole thing shows line (in delegate implementation of uitableviewcontroller) gets wrong quantity. seems indexpathforcell getting wrong cell returning wrong quantity?
// cell.quantity wrong item.quantity = cell.quantity for completeness sake, here's cellforrowatindexpath implementation cells being dequeued come view:
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) items 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 next time item.setzeroquantity = false } else { cell.cellquantity.text = string(item.quantity) } ..... .... .. . }
you need update stepper value in else clause in cellforrowatindexpath:
else { cell.cellquantity.text = string(item.quantity) cell.cellquantitystepper.value = double(item.quantity) } otherwise stepper retains value previous time cell used.
Comments
Post a Comment