ios UIPanGestureRecognizer指针位置

Jac*_*nkr 20 ios uipangesturerecognizer

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

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

上面的代码将记录我当前平移的相对位置,但是如何获得我所在视图的绝对位置?

我只是想把它滑到UIImageView用户手指的任何地方.

sch*_*sch 34

translationInView为您提供平移转换(x已更改多少),而不是视图中平移的位置(x的值).如果您需要平移的位置,则必须使用该方法locationInView.

您可以找到相对于视图的坐标,如下所示:

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

或者相对于superview:

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

或者相对于窗口:

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

  • 使用`UIGestureRecognizer`的`view`属性而不是`self`是不是更好?它允许您在不破坏事物的情况下移动手势识别器.同样对于窗口位置,它足以通过`nil`. (7认同)