Created
January 23, 2011 01:54
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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