Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UITableView: how to disable dragging of items to a specific row?

I have a UITableView with draggable rows and I can add/remove items. The datasource is a NSMutableArray.

Now, if I move the row with "Add new functionality" the app crashes because the dataSource is smaller since such row has not been added yet.

So I've modified this code:

- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {         if (indexPath.row >= [dataList count]) return NO;         return YES;     } 

And now I can't move it anymore. However I can still move the other rows after such row and consequently the code crashes.

How can I solve this ? Is there a way to disable the dragging "to" specific rows and not only from ?

thanks

like image 594
aneuryzm Avatar asked Aug 09 '11 13:08

aneuryzm


2 Answers

This is exactly what the UITableViewDelegate method

-tableView:targetIndexPathForMoveFromRowAtIndexPath:toProposedIndexPath:

is for. Will it suit your purposes? Here's the documentation.

like image 51
GarlicFries Avatar answered Sep 23 '22 15:09

GarlicFries


The previous answers and the documentation (see this and this, as mentioned in the other answers) are helpful but incomplete. I needed:

  • examples
  • to know what to do if the proposed move is not okay

Without further ado, here are some

Examples

Accept all moves

- (NSIndexPath *)tableView:(UITableView *)tableView     targetIndexPathForMoveFromRowAtIndexPath:(NSIndexPath *)sourceIndexPath                          toProposedIndexPath:(NSIndexPath *)proposedDestinationIndexPath {     return proposedDestinationIndexPath; } 

Reject all moves, returning the row to its initial position

- (NSIndexPath *)tableView:(UITableView *)tableView     targetIndexPathForMoveFromRowAtIndexPath:(NSIndexPath *)sourceIndexPath                          toProposedIndexPath:(NSIndexPath *)proposedDestinationIndexPath {     return sourceIndexPath; } 

Reject some moves, returning any rejected row to its initial position

- (NSIndexPath *)tableView:(UITableView *)tableView     targetIndexPathForMoveFromRowAtIndexPath:(NSIndexPath *)sourceIndexPath                          toProposedIndexPath:(NSIndexPath *)proposedDestinationIndexPath {     if (... some condition ...) {         return sourceIndexPath;     }     return proposedDestinationIndexPath; } 
like image 35
Matt Fenwick Avatar answered Sep 24 '22 15:09

Matt Fenwick