21
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.

Jacksonkr
  • 31,583
  • 39
  • 180
  • 284

3 Answers3

35

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);
}
sch
  • 27,436
  • 3
  • 68
  • 83
  • 7
    Isn't it better to use `UIGestureRecognizer`'s `view` property instead of `self`? It allows you to move the gesture recognizer around without breaking things. Also for window location, it's sufficient to pass `nil`. – Rudolf Adamkovič Mar 28 '13 at 14:49
2

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)
budiDino
  • 13,044
  • 8
  • 95
  • 91
  • Thanks! Can post the proper call for getting absolute/non-relative location within the window or view? Thanks in advance! – 01GOD Mar 20 '21 at 01:20
0

I think a simple way of something like this is to get the x and y of the touch and tracking it, once it has 2 points (say X:230 Y:122) you set the scroll of the UIScroll view to the x and y.

miken32
  • 42,008
  • 16
  • 111
  • 154
Allison
  • 2,213
  • 4
  • 32
  • 56