Cover by Vandad Nahavandipoor

Safari, the world’s most comprehensive technology and business learning platform.

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required

O'Reilly logo

3.11. Moving Cells and Sections in Table Views

Problem

You want to move and shuffle cells and sections inside a table view, with smooth and intuitive animations.

Solution

Use the moveSection:toSection: method of the table view to move a section to a new position. You can also use the moveRowAtIndexPath:toIndexPath: method to move a table view cell from its current place to a new place.

Discussion

Moving table view cells and sections differs from exchanging them. Let’s have a look at an example that will make this easier to understand. Let’s say you have three sections in your table view: Sections A, B, and C. If you move Section A to Section C, the table view will notice this move and will then shift Section B to the previous position of Section A, and will move Section B to the previous position of Section B. However, if Section B is moved to Section C, the table view will not have to move Section A at all, as it is sitting on top and doesn’t interfere with the repositioning of Section B and C. In this case, Section B will be moved to Section C and Section C to Section B. The same logic will be used by the table view when moving cells.

To demonstrate this, let’s create a table view and preload it with three sections, each of which contains three cells of its own. Let’s start with the header file of our view controller:

#import <UIKit/UIKit.h> @interface Moving_Cells_and_Sections_in_Table_ViewsViewController : UIViewController <UITableViewDelegate, UITableViewDataSource> @property (nonatomic, ...

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required