Search code examples
objective-cioscocoa-touchuigesturerecognizeruitouch

How can I get touch offset when using UITouch


How can I get touch offset when using UITouch? I am doing a project like a remote control. I have a view set to multi-touched and I want the view to act like a touch pad for Mac, so I need the touch offsets when people move to control the mouse. Any ideas?


Solution

  • This can be accomplished with a UIPanGestureRecognizer by measuring the diagonal distance from the center of the screen to the current touch location.

    #import <QuartzCore/QuartzCore.h>
    

    Declare the gesture and hook it to self.view so that the entire screen responds to touch events.

    UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(myPanRecognizerMethod:)];
    [pan setDelegate:self];
    [pan setMaximumNumberOfTouches:2];
    [pan setMinimumNumberOfTouches:1];
    [self.view setUserInteractionEnabled:YES];
    [self.view addGestureRecognizer:pan];
    

    Then in this method, we use the gesture recognizers state: UIGestureRecognizerStateChanged to update and integer that measures the diagonal distance between touch location and screen center as the touch location changes.

    -(void)myPanRecognizerMethod:(id)sender
    {
        [[[(UITapGestureRecognizer*)sender view] layer] removeAllAnimations];
        if ([(UIPanGestureRecognizer*)sender state] == UIGestureRecognizerStateChanged) {
            CGPoint touchLocation = [sender locationOfTouch:0 inView:self.view];
            NSNumber *distanceToTouchLocation = @(sqrtf(fabsf(powf(self.view.center.x - touchLocation.x, 2) + powf(self.view.center.y - touchLocation.y, 2))));
            NSLog(@"Distance from center screen to touch location is == %@",distanceToTouchLocation);
        }
    }