UIView上での左右のスワイプを検出する
UIViewを継承して以下のコードを貼り付ける。
float horizontalTolerance = 10f; public float HorizontalTolerance { get { return horizontalTolerance; } set { horizontalTolerance = value; } } float verticalTolerance = 6f; public float VerticalTolerance { get { return verticalTolerance; } set { verticalTolerance = value; } } private UISwipeGestureRecognizerDirection swipeType = UISwipeGestureRecognizerDirection.Down; private PointF startPoint = new PointF (0, 0); private long startTicks = 0; private PointF GetCurrentPoint (NSSet touches) { return (touches.AnyObject as UITouch).LocationInView (this); } public override void TouchesBegan (NSSet touches, UIEvent evt) { base.TouchesBegan (touches, evt); startPoint = GetCurrentPoint (touches); swipeType = UISwipeGestureRecognizerDirection.Down; startTicks = DateTime.Now.Ticks; } public override void TouchesMoved (NSSet touches, UIEvent evt) { base.TouchesMoved (touches, evt); PointF currentPoint = GetCurrentPoint (touches); if (Math.Abs (startPoint.X - currentPoint.X) >= HorizontalTolerance && Math.Abs (startPoint.Y - currentPoint.Y) <= VerticalTolerance) { if (startPoint.X < currentPoint.X) { swipeType = UISwipeGestureRecognizerDirection.Left; } else { swipeType = UISwipeGestureRecognizerDirection.Right; } } } public override void TouchesEnded (NSSet touches, UIEvent evt) { base.TouchesEnded (touches, evt); PointF currentPoint = GetCurrentPoint (touches); if (swipeType == UISwipeGestureRecognizerDirection.Down) return; long ticks = DateTime.Now.Ticks - startTicks; float diff = Math.Abs (startPoint.X - currentPoint.X); double speed = diff / ticks; // なにかの処理。 }
UIViewを継承しているclassであればどれでも使える(使い道は別として)。
追記 2011/08/01
UISwipeGestureRecognizerを使う方法があった。