Search code examples
swiftcheckboxtableviewreloaddata

reloadData after moveRowAtIndexPath


I have one tableview with two sections: ingredients to buy and ingredients that user has already. So, basically when uses does shopping he/she passes one ingredient from one list to another.

Here is tableView:cellForRowAtIndexPath

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
   let cell = tableView.dequeueReusableCellWithIdentifier("IngredientCell", forIndexPath: indexPath) as! IngredientCell
   cell.checkbox.checkboxDelegate = self
   cell.checkbox.checkboxIndex = indexPath
   ...
}

I will call this one: (I included stateOfCheckbox - every tableviewcell includes a custom button with a role of a checkbox - basically this one gives me the direction from/to I will do the move).

 func doChange(stateOfCheckbox: Bool, row: Int){
   let fromSection = stateOfCheckbox ? 0 : 1
   let toSection = stateOfCheckbox ? 1 : 0

   let fromIndexPath = NSIndexPath(forRow: row, inSection: fromSection)
   let toIndexPath = NSIndexPath(forRow: 0, inSection: toSection)

   let dataPiece = ingredients[fromIndexPath.section][fromIndexPath.row]
   ingredients[toIndexPath.section].insert(dataPiece, atIndex: toIndexPath.row)
   ingredients[fromIndexPath.section].removeAtIndex(fromIndexPath.row)

   ingredientsTableView.moveRowAtIndexPath(fromIndexPath, toIndexPath: toIndexPath)
   ingredientsTableView.reloadData()
}

I wouldn't want to call reloadData, but when not called somehow table indexes got mixed up. Is it necessary? Or there is another way?

This is how is behaves if reloadData is not present. I don't want to reload everything and repaint again. What would be a best practice?

behaviour


Solution

  • I'm pretty sure the problem is not in the code you posted in your question. From what I'm seeing in the Gif, the following must be the case:

    If you check one, and afterwards check one below that, the index is shifted by one. What's actually going on: It still uses the old index from before the first one was checked. These indices will either need to be refreshed or - what I would prefer - determined when you're actually tapping it.