Making table cells reorderable

This example shows how to make UITableView cells reorderable:

Reorderable/Movable table cells

Last update: July 18, 2018 | Tested with: Xcode 9.4 and Xcode 10 Beta 4
  1. Use your NewspaperExample project from the introductory UITableViewController tutorial or download NewspaperExample.zip as a starting point.

  2. In StoriesTableViewController, overwrite the UIViewController method viewDidLoad and enable the editing mode for the UITableView:

    override func viewDidLoad() {
        super.viewDidLoad()
        self.tableView.isEditing = true
    }
  3. Enabling the edit mode causes delete buttons to be visible for all cells:

    Delete Buttons

    Disable the buttons by implementing these UITableViewDataSource methods:

    override func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle {
        return .none
    }
    
    override func tableView(_ tableView: UITableView, shouldIndentWhileEditingRowAt indexPath: IndexPath) -> Bool {
        return false
    }
  4. Enable the reorder control to move cells by overwriting tableView:moveRowAtIndexPath: and implement the method so that the elements in the underlying data list are updated:

    override func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
        let movedObject = self.headlines[sourceIndexPath.row]
        headlines.remove(at: sourceIndexPath.row)
        headlines.insert(movedObject, at: destinationIndexPath.row)
    }

    Hint: The table view is not reloaded after the move operation - UITableView trusts you to change the underlying model list accordingly. If you have a bug in your implementation, the UI will show the moved cell as moved by the user, but the underlying data object will have a different order.

    Hint: Many examples advise setting cell.showsReorderControl. This is not necessary, the control is automatically shown when you implement tableView:moveRowAtIndexPath:. Optionally you can overwrite canMoveRowAtIndexPath to enable the reorder control only for some rows.

  5. Run the app with ⌘R:

    Table move

Btn download 3c20f11b8e Download the finished example project
Btn read 3c0e607615 iOS Developer Blog
Btn subscribe 930758687e Subscribe: Email · Twitter
Btn training bbbdf557d2 Next iOS training: 25. Februar - 01. März 2019, Stuttgart
Btn about 5378472193 About me · Contact