Reorder the cells in a UITableView

   

Press Edit and unscramble the mystery word. Press down on the reordering control (horizontal grooves) until the cell is highlighted; then you can drag the cell up or down. Press Done when you’re done.

Source code in Reorder.zip

  1. main.m
  2. Class ReorderAppDelegate creates a TableViewController and puts it under a UINavigationController to make the TableViewController’s navigation bar visible.
  3. Class TableViewController: the data source has the methods tableView:canMoveRowAtIndexPath: and tableView:moveRowAtIndexPath:toIndexPath:.
  4. Reorder-Info.plist launches the app in landscape left.

Create the project

Remove two of the three Supported interface orientatations in the Reorder-Info.plist file in the Supporting Files folder of the Project Navigator. Only “Landscape (left home button)” should remain. (If more than one remains, the first one should be the orientation to be used at startup.) Remember to write a supportedInterfaceOrientations method in the view controller.

The methods

The table view controller is the table view’s data source and therefore contains the following methods. We have already seen the first three; they hold the data. The next two are new; they rearrange the data.

  1. numberOfSectionsInTableView:
  2. tableView:numberOfRowsInSection:
  3. tableView:cellForRowAtIndexPath:
  4. tableView:canMoveRowAtIndexPath:
  5. tableView:moveRowAtIndexPath:toIndexPath

The table view controller is also the table view’s delegate and therefore contains the following method. It prevents each cell from having a red minus sign.

  1. tableView:editingStyleForRowAtIndexPath:

T and H have no reordering controls

Thanks to the tableView:canMoveRowAtIndexPath: method of the data source, the T and H have no reordering controls. They can be pushed around by the other cells, but they must remain in the same relative order.

Things to try

  1. In the tableView:canMoveRowAtIndexPath: method of class TableViewController, change
    	if (![initial isEqualToString: @"T"] && ![initial isEqualToString: @"H"]) {
    		return YES;
    	}
    	return NO;
    
    to
    	return ![initial isEqualToString: @"T"] && ![initial isEqualToString: @"H"];
    
    It does the same thing.