ios UIPanGestureRecognizer pointer position

2019-03-24 07:42发布

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.

3条回答
beautiful°
2楼-- · 2019-03-24 07:48

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);
}
查看更多
聊天终结者
3楼-- · 2019-03-24 07:58

Swift

Relative location (CGPoint) of your gesture to self.view:

print( gesture.locationInView(self.view) )
查看更多
爷、活的狠高调
4楼-- · 2019-03-24 08:08

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.

I'm not sure exactly how I got to this answer... If it's not helpful don't down vote me I am still a noob D:

查看更多
登录 后发表回答