TTScrollView animate to page

I have been using Three20′s TTScrollView for some time now. I really enjoy the way I can use it like a UITableViewController and set the delegate and datasource. It is quite memory efficient with it’s ability to reuse views.

In my last project, my client wanted me to display photos is a timeline horizontally. In addition to flicking the photos I needed to support a next and previous button. I implemented this by calling [self.scrollView moveToPageAtIndex:currentPage+1 resetEdges:YES]; on my scrollview. This worked to show the next photo however, it did not animate the scroll. This was a big problem for the client.

I went about searching the internet for solutions. I only found others asking the same question. So i proceded to create my own solution.

I didn’t want to do anything too fancy so I came up with this code for my next and previous button handlers:

-(IBAction)nextImage:(id)sender
{
UIView *nextView = [self.scrollView pageAtIndex:currentPage + 1];
UIView *thisView = [self.scrollView pageAtIndex:currentPage];</p>

CGRect thisFrame = thisView.frame;
CGRect previousFrame = CGRectMake(thisFrame.origin.x - thisFrame.size.width, thisFrame.origin.y, thisFrame.size.width, thisFrame.size.height);

[UIView beginAnimations:@"next" context:NULL];
[UIView setAnimationDuration:0.3];
[UIView setAnimationBeginsFromCurrentState:YES];

nextView.frame = thisFrame;
thisView.frame = previousFrame;

[UIView commitAnimations];

[self.scrollView moveToPageAtIndex:currentPage+1 resetEdges:YES];
}

-(IBAction)previousImage:(id)sender
{
UIView *nextView = [self.scrollView pageAtIndex:currentPage - 1];
UIView *thisView = [self.scrollView pageAtIndex:currentPage];

CGRect thisFrame = thisView.frame;
CGRect previousFrame = CGRectMake(thisFrame.origin.x + thisFrame.size.width, thisFrame.origin.y, thisFrame.size.width, thisFrame.size.height);

[UIView beginAnimations:@"previous" context:NULL];
[UIView setAnimationDuration:0.3];
[UIView setAnimationBeginsFromCurrentState:YES];

nextView.frame = thisFrame;
thisView.frame = previousFrame;

[UIView commitAnimations];

[self.scrollView moveToPageAtIndex:currentPage-1 resetEdges:YES];
}
</code>

The code is pretty straightforward. It does the following:
1) Retrieve a pointer to the current and next/previous view.
2) Create CGRects to indicate where the two views will move to.
3) Set up UIView animations to animate the movement of the two views.
4) Finally, call moveToPageAtIndex on the scrollview to update the scrollview.

This works quite nicely. I would like to hear your comments and any other solutions you come up with. Feel free to comment.

I hope this helps out,

Dov