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

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

上面的代码将记录我当前平移的相对位置,但我怎样才能获得我所在视图的绝对位置?

我只是想将 a 滑动UIImageView到用户手指所在的位置。

4

3 回答 3

35

translationInView为您提供平移平移(x 变化了多少),而不是视图中平移的位置(x 的值)。如果你需要平底锅的位置,你必须使用方法locationInView

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

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

或者相对于superview:

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

或者相对于窗口:

- (void)pan:(UIPanGestureRecognizer *)gesture {
    NSLog(@"%f", [gesture locationInView:self.window].x);
}
于 2012-03-12T22:30:29.030 回答
2

斯威夫特 5

使用.location()返回CGPoint值的方法。[文档]

例如,您的手势与 的相对位置self.view

let relativeLocation = gesture.location(self.view)
print(relativeLocation.x)
print(relativeLocation.y)
于 2017-01-20T05:04:52.057 回答
0

我认为这样一种简单的方法是获取触摸的 x 和 y 并跟踪它,一旦它有 2 个点(比如 X:230 Y:122),您将 UIScroll 视图的滚动设置为 x 和 y .

我不确定我到底是如何得到这个答案的……如果没有帮助,请不要拒绝我,我仍然是菜鸟 D:

于 2012-03-12T22:40:55.223 回答