Swipe to change views

Luuk D. Jansen picture Luuk D. Jansen · Feb 8, 2011 · Viewed 16.6k times · Source

Is the following easy to code?

I have a tableview and when the user selects a cell a detail view is loaded. I want to allow the user to navigate throughout the items/detail-view representing the items in the tableview by left and right swipes, working in the same way as e.g. the home-screen of the iphone (e.g. while swiping, one page is moving off the screen and the next appears).

I have seen this implemented in the MobileRSS-APP, so it is possible, but I just have a hard-time figuring out the way to do it properly.

Thanks a million in advance! I am still trying to find my feet with cocoa-touch...

Answer

Thomas Clayson picture Thomas Clayson · Feb 8, 2011

The iphone home screen (springboard) works with a scroll view set to paging enabled.

UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0,0,self.view.frame.size.width, self.view.frame.size.height)];
[scrollView setPagingEnabled:YES];

Then, lets say there's two pages of apps to swipe through - you set the content size of the scroll view to twice the width of your view:

[scrollView setContentSize:CGSizeMake(self.view.frame.size.width*2, self.view.frame.size.height)];

And thats how that is done. :) I don't know if its the same for the MobileRSS-APP.

Things to bear in mind:

  1. This isn't the default way a table view works. You might get your app rejected by apple. A table view is meant to work by clicking.

  2. You could probably replicate the functionality without using a scroll view using touches methods and the navigation controller. A good tutorial describing how to detect swipes on your view is here: http://www.dosomethinghere.com/2009/07/23/simple-swipe-detection-in-the-iphone-sdk/

In the last method in that tutorial where there is the NSLog("swipe right") you could replace that with [self.navigationController popViewControllerAnimated:YES] which would replicate pressing the "back" button in the navigation bar.

I don't know what you could do for swipe left though..... if you wanted to do this on the table view you'll have to do some complicated maths determining how far the table view has been scrolled. Or you could test for touch events on the cells themselves, but thats something you wil have to look into. :)