Graphics Programs Reference
In-Depth Information
Moving Rows
To change the order of rows in a
UITableView
, you will use another method from the
UITableViewDataSource
protocol -
tableView:moveRowAtIndexPath:toIndexPath:
.
To delete a row, you had to send the message
deleteRowsAtIn-
dexPaths:withRowAnimation:
to the
UITableView
to confirm the deletion.
Moving a row, however, doesn't require confirmation; the table view moves the row on its
own authority and reports the move to its the data source by sending the message
tableView:moveRowAtIndexPath:toIndexPath:
. You just have to catch this
message to update your data source to match the new order.
But before we can implement the data source method, we need to give the
BNRItemStore
a method to change the order of
BNRItem
s in its
allItems
array. In
BNRItemStore.h
, declare this method.
- (void)moveItemAtIndex:(int)from
toIndex:(int)to;
Implement this method in
BNRItemStore.m
.
- (void)moveItemAtIndex:(int)from
toIndex:(int)to
{
if (from == to) {
return;
}
// Get pointer to object being moved so we can re-insert it
BNRItem *p = [allItems objectAtIndex:from];
// Remove p from array
[allItems removeObjectAtIndex:from];
// Insert p in array at new location
[allItems insertObject:p atIndex:to];
}
In
ItemsViewController.m
, implement
tableView:moveRowAtIndexPath:toIndexPath:
to update the store.
- (void)tableView:(UITableView *)tableView
moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath
toIndexPath:(NSIndexPath *)destinationIndexPath
{
[[BNRItemStore sharedStore] moveItemAtIndex:[sourceIndexPath row]