Swift 3, Swap two table cells

2.4k views Asked by At

I'm mostly a Java programmer but I've been learning swift and I've come across a bit of a roadblock.

I'm creating a matching definition game using a UITableView. The user can select one cell and then select another to swap their positions. Now the problem is that UITableViews method of moveRow only moves the first argument to the second arguments position. This creates a cascade effect when the gap is greater than 0.

I was curious if there is a simple way to swap the position of two cells in a table view perfectly.

For example if you had cells 1,2,3,4,5 and you select 2 and 4 the new pattern would be: 1,4,3,2,5. Currently it would appear as 1,3,4,2,5 as it only moves the first selected cell.

Any help here would be appreciated so much! Thank you.

1

There are 1 answers

1
vadian On BEST ANSWER

There are two steps to perform the action:

  • Exchange the items in the data source array (no visible effect). To preserve the indexes remove the item at the higher index and store it in a variable then the item at lower index. But insert first the item at lower then at higher index.
  • Wrapped in a beginUpdates / endUpdates block exchange the rows in the table view. The new indexes are calculated automatically.

    tableView.beginUpdates()
    tableView.moveRow(at: indexPath1, to: indexPath2)
    tableView.moveRow(at: indexPath2, to: indexPath1)
    tableView.endUpdates()
    

    Note: If you are using the move operations you must not call reloadData() afterwards.