Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom UITableView reorder

I'm wondering if anyone has a link to a good tutorial or can point me in the right direction to recreate the 'drag to reorder' cells in a UITableView like Epic Win App. The basic idea is you tap and hold on a list item and then you drag to where you want the item to be. Any help would be greatly appreciated.

like image 756
Pudgeball Avatar asked Oct 25 '10 00:10

Pudgeball


1 Answers

The simplest way, using the built-in methods, is as follows:

First, set your table cell to have shows reorder control on. Simplest example (using ARC):

This is assuming NSMutableArray *things has been created somewhere else in this class

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:@"do not leak me"];
    if (!cell) {
        cell = [[UITableViewCell alloc] init];
        cell.showsReorderControl = YES;
    }
    cell.textLabel.text = [things objectAtIndex:indexPath.row];
    return cell;
}

Implement your two UITableViewDelegate methods, like this:

This method tells the tableView it is allowed to be reordered

-(BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}

This is where the tableView reordering actually happens

-(void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath {
    id thing = [things objectAtIndex:sourceIndexPath.row];
    [things removeObjectAtIndex:sourceIndexPath.row];
    [things insertObject:thing atIndex:destinationIndexPath.row];

}

and then somehow, somewhere, set editing to true. This is one example of how you can do this. The tableView must be in editing mode in order for it to be reordered.

- (IBAction)doSomething:(id)sender {
    self.table.editing = YES;
}

Hope that serves as a concrete example.

like image 96
Dan Rosenstark Avatar answered Oct 26 '22 23:10

Dan Rosenstark