I was creating a small todo app for fun, had a UITableView Set Up populated by an SQLite database, wanted to keep the first cell the “Inbox” and have it not be moved, or have any other cell be able to be sorted above it. After hours of trying to figure out the method to do this I figured out that a few things needed to be done in a few methods:
First, tell the <b>canMoveRowAtIndexPath</b> method that the first row can not be moved when the table is in edit mode:
|
1 2 3 4 5 6 7 8 |
// Override to support conditional rearranging of the table view. - (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath { // Return NO if you do not want the item to be re-orderable. if (indexPath.row == 0) // Don't move the first row return NO; return YES; } |
Second, tell the <b>canEditRowAtIndexPath</b> that the row can not be deleted:
|
1 2 3 4 5 6 7 |
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath { // Return NO if you do not want the specified item to be editable. if (indexPath.row == 0) return NO; return YES; } |
Finally, tell the <b>targetIndexPathForMoveFromRowAtIndexPath</b> method to not let anything be dragged above the first cell, but let the rest of the cells swap any where else they want:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
- (NSIndexPath *)tableView:(UITableView *)tableView targetIndexPathForMoveFromRowAtIndexPath:(NSIndexPath *)sourceIndexPath toProposedIndexPath:(NSIndexPath *)proposedDestinationIndexPath { //This makes it so every row except the first can be moved, and no row can be moved above the first row. NSIndexPath *indexPath = nil; if (proposedDestinationIndexPath.row == 0) { indexPath = [NSIndexPath indexPathForRow:1 inSection:0]; } else { return proposedDestinationIndexPath; } return indexPath; } |
Hope this helps anyone that was having the same problem.