4.7. 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 C 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 implementation file of our view controller:
#import "ViewController.h"staticNSString*CellIdentifier=@"CellIdentifier";@interfaceViewController()<UITableViewDelegate,UITableViewDataSource>@property ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access