Quantcast
Viewing all articles
Browse latest Browse all 3

Detect Single Tap in UIScrollView

If you’ve ever been using a UIScrollView and had a need to detect a single tap, I hear you. In the Savini Rims and Rides iPhone application, I had a horizontal scrollview of six cars as one element of the user interface. Selecting on a car (tapping once) was to launch a video. Trouble is, UIScrollView eats the single tap I was after.

Let me show you what I came up with to catch single taps within a UIScrollView. First, I created a subclass of UIScrollView as follows:

Subclass UIScrollView

@interface AppScrollView : UIScrollView  { }   @end

The implementation of the AppScrollView is all of two methods, the initialization code and one method to manage touch events. The trick in detecting one touch is to look for the touchesEnded event, and within that method, check to see if the user is dragging when the event is triggered. If not dragging, pass the event up to the next responder – most likely, your class that contains an AppScrollView object.

AppScrollView Implementation

#import "AppScrollView.h"   @implementation AppScrollView   - (id)initWithFrame:(CGRect)frame  {   return [super initWithFrame:frame]; }   - (void) touchesEnded: (NSSet *) touches withEvent: (UIEvent *) event  {	   // If not dragging, send event to next responder   if (!self.dragging)      [self.nextResponder touchesEnded: touches withEvent:event];    else     [super touchesEnded: touches withEvent: event]; }   @end

From here we can create a new class that includes a AppScrollView object:

Class Interface Using AppScrollView

#import <UIKit/UIKit.h>   @class AppScrollView;   @interface SomeClass : UIViewController <UIScrollViewDelegate> {   AppScrollView *scrollView;   ... }   @end

Now, inside the implementation of the SomeClass class, all we need to do is look for the touchesEnded event that was passed up the responder chain. For example, a skeleton of the class using AppScrollView may look as follows:

Class Implementation Receiving Single Tap

#import "AppScrollView.h"   @implementation SomeClass   ...   - (void) touchesEnded: (NSSet *) touches withEvent: (UIEvent *) event  {   // Process the single tap here   ... }   ...   @end

As with everything else, it’s easy once you know the trick.


Viewing all articles
Browse latest Browse all 3

Trending Articles