blabus
blabus

Reputation: 845

What is the purpose of the delegate method 'canMoveRowAtIndexPath'?

I'm working on a UI component right now, and as it behaves similarly to UITableView, I'm heavily modeling the delegate and data source protocols after those of UITableView. However, I noticed one method that I don't quite understand- 'canMoveRowAtIndexPath'.

This essentially allows the delegate to specify whether it wants the given cell to be 'movable'. However, wouldn't dropping another movable cell into a higher index than the immovable cell (i.e. 'above' it in the table) cause it to indirectly move anyway? (since every cell below the moved one would be pushed down one row).

So basically, my question is what is the point of this method? Can anyone provide an example use-case for it? Because I'm debating whether I should bother including it in my component or not.

If anything, I would think perhaps a more useful delegate method would be something such as 'canMoveRowInSection', which would allow you to specify whether any rows in a given section can be moved. That would then allow you to disable reordering of a particular section, and moving other rows outside of that section would not affect the ordering of the rows inside it.

I know Apple engineers provided this method for a reason, I just can't see what that reason might be.

Thanks for any insight!

Upvotes: 1

Views: 1241

Answers (1)

WrightsCS
WrightsCS

Reputation: 50717

canMoveRowAtIndexPath tells the UITableView that if the table is in editing mode, the cells (or cell, if you choose specifically) can be moved up and down.

It's up to you the developer to handle the other side of that move.

For instance, say you have an array (NSMutableArray to be exact) of "A", "B", "C" and you want to rearrange that array to be "B", "C", "A". You need to make that change in the array based on the location of the cell being moved and save that array.

Example

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

- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
    id objectToMove = [[array objectAtIndex:fromIndexPath.row] retain];
    [array removeObjectAtIndex:fromIndexPath.row];
    [array insertObject:objectToMove atIndex:toIndexPath.row];
    [objectToMove release];
}

Section Example

This example says that if the table section is 0, then no cells can move. Any other section (say you have 3), those cells in section 1 and 2 CAN move. You will still need to handle the array accordingly.

-(BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath 
{
    if ( indexPath.section == 0 )
        return NO;

    return YES;
}

Upvotes: 4

Related Questions