Skip to content

Instantly share code, notes, and snippets.

@siannopollo
Created January 23, 2011 01:54
Show Gist options
  • Save siannopollo/791725 to your computer and use it in GitHub Desktop.
Save siannopollo/791725 to your computer and use it in GitHub Desktop.
A UIVIew class to detect swipes, and forward the message on to a delegate which can react to the swipe
#import <UIKit/UIKit.h>
@protocol SwipeViewDelegate;
@interface SwipeView : UIView {
id <SwipeViewDelegate> swipeDelegate;
int touchBeganX, touchBeganY;
int touchMovedX, touchMovedY;
}
@property (nonatomic, retain) id swipeDelegate;
@end
@protocol SwipeViewDelegate <NSObject>
- (void)viewDidSwipeLeft:(SwipeView *)swipeView;
- (void)viewDidSwipeRight:(SwipeView *)swipeView;
@end
// Swipe detection snagged from here: http://www.dosomethinghere.com/2009/07/23/simple-swipe-detection-in-the-iphone-sdk
#import "SwipeView.h"
@implementation SwipeView
@synthesize swipeDelegate;
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
CGPoint pt;
NSSet *allTouches = [event allTouches];
if ([allTouches count] == 1) {
UITouch *touch = [[allTouches allObjects] objectAtIndex:0];
if ([touch tapCount] == 1) {
pt = [touch locationInView:self];
touchBeganX = pt.x;
touchBeganY = pt.y;
}
}
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
CGPoint pt;
NSSet *allTouches = [event allTouches];
if ([allTouches count] == 1) {
UITouch *touch = [[allTouches allObjects] objectAtIndex:0];
if ([touch tapCount] == 1) {
pt = [touch locationInView:self];
touchMovedX = pt.x;
touchMovedY = pt.y;
}
}
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
NSSet *allTouches = [event allTouches];
if ([allTouches count] == 1) {
int diffX = touchMovedX - touchBeganX;
int diffY = touchMovedY - touchBeganY;
if (diffY >= -20 && diffY <= 20) {
if (diffX > 20) {
NSLog(@"swipe right");
if (swipeDelegate) [swipeDelegate viewDidSwipeRight:self];
} else if (diffX < -20) {
NSLog(@"swipe left");
if (swipeDelegate) [swipeDelegate viewDidSwipeLeft:self];
}
}
}
}
- (void)dealloc {
if (swipeDelegate) [swipeDelegate release];
[super dealloc];
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment