How to make UITableView rearrangeable?
I'm trying to make my UITableView editable so you can move the cells around. Right now when I click the edit button, it only lets me delete but not re-arrange.
The methods I have are:
Code:
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
return YES;
}
- (void)setEditing:(BOO开发者_如何学JAVAL)editing animated:(BOOL)animate
{
[self.routineTableView setEditing: !self.routineTableView.editing animated:YES];
if (self.routineTableView.editing)
[self.navigationItem.leftBarButtonItem setTitle:@"Done"];
else
[self.navigationItem.leftBarButtonItem setTitle:@"Edit"];
}
-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (editingStyle == UITableViewCellEditingStyleDelete)
{
NSManagedObjectContext *context = [self.fetchedResultsController managedObjectContext];
[context deleteObject:[self.fetchedResultsController objectAtIndexPath:indexPath]];
NSLog(@"fetched results : \n%@\n",[self.fetchedResultsController fetchedObjects]);
NSError *error = nil;
if (![managedObjectContext save:&error])
{
// Handle the error.
}
}
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
return YES;
}
In order to implement reordering rows correctly, the table view data source should implement methods like :
-(BOOL)tableView:(UITableView *)tableView
canMoveRowAtIndexPath:(NSIndexPath *)indexPath;
-(void)tableView:(UITableView *)tableView
moveRowAtIndexPath:(NSIndexPath *)fromIndexPath
toIndexPath:(NSIndexPath *)toIndexPath;
and the its delegate could implement :
-(NSIndexPath *)tableView:(UITableView *)tableView
targetIndexPathForMoveFromRowAtIndexPath:(NSIndexPath *)sourceIndexPath
toProposedIndexPath:(NSIndexPath *)proposedDestinationIndexPath;
There is also this page giving you examples of code.
You've got to read the documentation. You can also get the related sample code there.
When a table view enters editing mode and when users drag a reordering control, the table view sends a series of messages to its data source and delegate, but only if they implement these methods. These methods allow the data source and delegate to restrict whether and where a row can be moved as well to carry out the actual move operation.
精彩评论