UIViewでスワイプを検出する方法
スワイプ(ページをめくるような動作)を検出するコードです。あまりサンプルがなかったので、iPhoneデベロッパーズクックブックを参考に。速度も検出できるので、動作によって遅くor速くアニメーションを実行するなどの制御ができます。
MyView.h
#import <UIKit/UIKit.h> @interface MyView : UIView { NSDate *startTime; } @property (nonatomic, retain) NSDate *startTime; @end
MyView.m
#import "MyView.h" #define HORIZ_SWIPE_MIN 12 #define VERT_SWIPE_MAX 8 #define SWIPE_NON 0 #define SWIPE_LEFT 1 #define SWIPE_RIGHT 2 @implementation MyView @synthesize startTime; CGPoint startPt; int swipe_direction; // タッチ開始 - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{ startPt = [[touches anyObject] locationInView:self]; startTime = [[NSDate date] retain]; swipe_direction = SWIPE_NON; } // 移動 - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{ CGPoint curPt = [[touches anyObject] locationInView:self]; // 水平のスワイプを検出 if(fabsf(startPt.x - curPt.x) >= HORIZ_SWIPE_MIN && fabsf(startPt.y - curPt.y) <= VERT_SWIPE_MAX){ if(startPt.x < curPt.x){ swipe_direction = SWIPE_LEFT; }else{ swipe_direction = SWIPE_RIGHT; } } } // タッチ終了 - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{ CGPoint curPt = [[touches anyObject] locationInView:self]; if(swipe_direction != SWIPE_NON){ // スワイプの速度を検出 NSTimeInterval dt = -[startTime timeIntervalSinceNow]; int dx = fabsf(startPt.x - curPt.x); double speed = dx / dt; NSLog([NSString stringWithFormat:@"dir:%i, dx:%i, dt:%f, speed:%f", swipe_direction, dx, dt, speed]); } } - (void)dealloc { [startTime release]; [super dealloc]; } @end
実行結果はこんな感じ。
2009-03-05 23:49:38.269 swipe[2143:20b] dir:2, dx:90, dt:0.135690, speed:663.276569 2009-03-05 23:49:40.197 swipe[2143:20b] dir:2, dx:68, dt:1.569752, speed:43.318944 2009-03-05 23:49:42.022 swipe[2143:20b] dir:1, dx:94, dt:1.280833, speed:73.389741 2009-03-05 23:49:42.574 swipe[2143:20b] dir:2, dx:27, dt:0.079615, speed:339.132086 2009-03-05 23:49:44.839 swipe[2143:20b] dir:2, dx:39, dt:0.087758, speed:444.403905 2009-03-05 23:49:45.479 swipe[2143:20b] dir:1, dx:134, dt:0.062301, speed:2150.848988