Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ios UIPanGestureRecognizer pointer position

UIPanGestureRecognizer *panRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(pan:)];
[self addGestureRecognizer:panRecognizer];

- (void)pan:(UIPanGestureRecognizer *)gesture {
    NSLog(@"%f", [gesture translationInView:self].x);
}

The above code will log the relative position of my current pan, but how can I get the absolute position for the view I'm in?

I'm simply just wanting to slide a UIImageView to wherever the user's finger is.

like image 211
Jacksonkr Avatar asked Mar 12 '12 22:03

Jacksonkr


2 Answers

translationInView gives you the pan translation (how much x has changed) and not the position of the pan in the view (the value of x). If you need the position of the pan, you have to use the method locationInView.

You can find the coordinates relatively to the view as follows:

- (void)pan:(UIPanGestureRecognizer *)gesture {
    NSLog(@"%f", [gesture locationInView:self].x);
}

Or relatively to the superview:

- (void)pan:(UIPanGestureRecognizer *)gesture {
    NSLog(@"%f", [gesture locationInView:self.superview].x);
}

Or relatively to the window:

- (void)pan:(UIPanGestureRecognizer *)gesture {
    NSLog(@"%f", [gesture locationInView:self.window].x);
}
like image 162
sch Avatar answered Nov 04 '22 01:11

sch


Swift 5

Use the method .location() that returns a CGPoint value. [documentation]

For example, relative location of your gesture to self.view:

let relativeLocation = gesture.location(self.view)
print(relativeLocation.x)
print(relativeLocation.y)
like image 2
budiDino Avatar answered Nov 04 '22 01:11

budiDino