Question

I'm trying to have it so when the pan gesture it ends, checks to see if the end location is within a certain area, in my case a square. I have the following code, and it more less works but for some reason even when the pan ends in the square, it's saying its not.

-(void)panHandler:(UIPanGestureRecognizer*)recognizer{
CGPoint translation = [recognizer translationInView:self.view];
switch (recognizer.state){
    case UIGestureRecognizerStateBegan:
        _stickImage.center = CGPointMake(_stickImage.center.x + translation.x, _stickImage.center.y + translation.y);
        break;

    case UIGestureRecognizerStateChanged:
        _stickImage.center = CGPointMake(_stickImage.center.x + translation.x, _stickImage.center.y + translation.y);
        [recognizer setTranslation:CGPointMake(0, 0) inView:self.view];
        break;

    case UIGestureRecognizerStateEnded:
        NSLog(@"Ended");
        if(translation.x > _rectView.frame.origin.x && translation.x < (_rectView.frame.origin.x + _rectView.frame.size.width)){
            if(translation.y > _rectView.frame.origin.y && translation.y < (_rectView.frame.origin.y + _rectView.frame.size.height)){
                NSLog(@"In the grid!");
            }
        }
        else{
            NSLog(@"out of the grid");
        }

        break;

    default:
        break;
}

}

Can I use the translation x and y locations like i did? Or how will I find if the pan end location is in the square? Any help will be much appreciated thanks!

Was it helpful?

Solution

translationInView: does not give the location of the touch, it tells you how far the touch has moved since the last call to setTranslation:inView:

The method you want is locationInView:

CGPoint location = [recognizer locationInView:recognizer.view];

if(CGRectContainsPoint(_rectView.frame, location)){
    NSLog(@"Inside!");
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top