Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically move/animate a UITableView row from one position to another

I have a UITableView and I want to programmatically move one row from position N1 to position N2 and I would like it to animate from the old location to the new. I've looked through the UITableView documentation and I'm only seeing inserts, reloads, and deletes. Do you know of a way I can do this programmatically?

A couple of notes:

  • I know that I can animate the deletion from location N1 and animate the insertion to location N2 at the same time. That's my fallback, but I'd like the user to understand that it is truly moving from N1 to N2.

  • I'm not talking about allowing the user to drag it from one place to another. I understand how to do that, I'm looking for a way to initiate and animate the move programmatically.

like image 718
Kenny Wyland Avatar asked Feb 24 '11 19:02

Kenny Wyland


2 Answers

I've dealt with something kind of like this in the past and the solution is not pretty but it does work.

Basically you have to do some math to calculate where on the screen the row is. Then adjust that based on the y property of the contentOffset of your UITableView.

You can do that like this:

[myView convertPoint:localPosition toView:nil];

Then you would construct a new UIView that's identical to your view. Set its frame to be directly on top of the UITableViewCell you're trying to move. Add it as a subview of your app's main UIWindow.

You'll want to set userInteractionEnabled or scrollEnabled to NO on your UITableView while all of this is going on so that the user can't muck with the position of things throughout the process (just remember to set it back to YES when everything is done animating).

Then animate it to the new position however makes the most sense.

I understand you may have to scroll the UITableView in the process of all of this, which complicates things considerably, but you can animate that scrolling as well.

You'll of course have to do similar operations on the row you're animating to if it is necessary in your app.

Like I said its not easy or pretty. But I do understand what you're trying to accomplish and I think the effect is super awesome when it's pulled off properly.

If anyone has a better idea of how to pull this off without going insane I'd love to know, but this type of implementation is the best I've been able to do.

like image 81
Jake Marsh Avatar answered Nov 18 '22 07:11

Jake Marsh


[table beginUpdates];
[table moveRowAtIndexPath:indexPath toIndexPath:destIndexPath];
[table endUpdates];
like image 1
Altynbek Usenbekov Avatar answered Nov 18 '22 07:11

Altynbek Usenbekov