Search code examples
iphoneiosobjective-ctouchtouchesmoved

In touchesMoved, how to detect a slide motion and then a stop?


I can already detect a slide motion in touchesMoved, but I was wondering how to detect a slide and then detect when the slide stops but the finger is still pressed on screen?

Here's my code so far:

-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{

if(self.tutorialView.alpha != 1.0 || self.tutorialView.hidden)
{

UITouch *touch = [touches anyObject];
CGPoint gestureEndPoint = [touch locationInView:self.view];

int dx = abs(gestureStartPoint.x - gestureEndPoint.x);
int dy = -1 * (gestureEndPoint.y - gestureStartPoint.y);

if(dx > 20) {
    // too much left/right, so don't do anything
    return;
}

if((gestureStartPoint.x - gestureEndPoint.x) < 20 && (gestureStartPoint.x - gestureEndPoint.x) > -20)
{

    if((gestureStartPoint.y - gestureEndPoint.y) > (gestureStartPoint.x - gestureEndPoint.x))
    {

        if(dy > 0)
        {

            // User has made an upwards slide motion

        }

        else
        {

            // User has made a downwards slide motion

    else
        self.number = 0;

    }

    }

}

}

}

Solution

  • you can use timer, in touchesMoved, invalid the old timer and create a new one, which will fire the "stop motion detected" selector.

    something like this

    -(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
         //NSTimer *_timer; // as an iver
        if (/* check move distance, if big enough */) {
            [_timer invalidate];
            _timer = [NSTimer scheduledTimerWithTimeInterval:0.2 target:self selector:@selector(slideStopped) userInfo:nil repeats:NO];
        }
    }
    
    -(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
         [_timer invalidate]; // you may handle touch up differently and don't want slideStopped get called
         _timer = nil;
    }
    
    - (void)slideStopped {
        // handle slide stopped event
    }