iOS UIPanGestureRecognizer 指针位置

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

- (void)pan:(UIPanGestureRecognizer *)gesture {
    NSLog(@"%f", [gesture translationInView:self].x);
}
上述代码将记录当前pan手势的相对位置,但如何获取我所在视图的绝对位置?
我只是想将UIImageView滑动到用户手指所在的位置。

"the absolute position for the view I'm in" 的意思是什么? - sch
3个回答

35

translationInView 返回的是平移的距离(x轴方向变化的大小),而不是手势在视图中的位置(x的值)。如果你需要获取手势在视图中的位置,你需要使用方法 locationInView

你可以按如下方式相对于视图获取坐标:

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

或相对于父视图:

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

或者相对于窗口:

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

7
使用UIGestureRecognizerview属性比使用self更好,这可以让你移动手势识别器而不破坏任何东西。关于窗口位置,传递nil就足够了。 - Rudolf Adamkovič

2

Swift 5

使用方法.location(),该方法返回一个CGPoint值。[文档]

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

let relativeLocation = gesture.location(self.view)
print(relativeLocation.x)
print(relativeLocation.y)

谢谢!可以发布获取窗口或视图内绝对/非相对位置的正确调用吗?先行致谢! - 01GOD

0
我认为一个简单的方法就是获取触摸的X和Y坐标并跟踪它们,一旦有了两个点(比如X:230 Y:122),你就可以将UIScrollView的滚动设置为这些X和Y坐标。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接