我的观点中添加了UIPanGestureRecognizer
问题是,当触摸被识别为平移手势时,它必须移动几个点,并且我无法在UIGestureRecognizerStateBegan
状态下提取原始触摸位置。
在此状态下,translationInView:
为(0,0),任何后续移动都是从此点开始计算的,而不是从原始位置计算出来的。
有没有办法从手势识别器本身提取原始位置,还是需要覆盖touchesBegan:
方法?
答案 0 :(得分:7)
您应该能够为手势识别器设置delegate
并实施
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
获得初步接触。
答案 1 :(得分:3)
您可以通过实施自定义PanGestureRecognizer
来解决此问题,该自定义保存原始触摸点并使其可供调用者使用。
我走了这条路,因为我也想控制移动的距离以触发平移手势。
这对你的情况来说可能有点过头了,但是效果很好而且听起来不那么困难。
要获得接触点坐标,只需拨打:
[sender touchPointInView:yourView]
而不是:
[sender locationInView:yourView]
以下是PanGestureRecognizer.m
的代码:
#import "PanGestureRecognizer.h"
#import <UIKit/UIGestureRecognizerSubclass.h>
@implementation PanGestureRecognizer
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
[super touchesBegan:touches withEvent:event];
UITouch *touch = [touches anyObject];
// touchPoint is defined as: @property (assign,nonatomic) CGPoint touchPoint;
self.touchPoint = [touch locationInView:nil];
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
[super touchesMoved:touches withEvent:event];
UITouch *touch = [touches anyObject];
CGPoint p = [touch locationInView:nil];
// customize the pan distance threshold
CGFloat dx = fabs(p.x-self.touchPoint.x);
CGFloat dy = fabs(p.y-self.touchPoint.y);
if ( dx > 2 || dy > 2) {
if (self.state == UIGestureRecognizerStatePossible) {
[self setState:UIGestureRecognizerStateBegan];
}
else {
[self setState:UIGestureRecognizerStateChanged];
}
}
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
[super touchesEnded:touches withEvent:event];
if (self.state == UIGestureRecognizerStateChanged) {
[self setState:UIGestureRecognizerStateEnded];
}
else {
[self setState:UIGestureRecognizerStateCancelled];
}
}
- (void) reset
{
}
// this returns the original touch point
- (CGPoint) touchPointInView:(UIView *)view
{
CGPoint p = [view convertPoint:self.touchPoint fromView:nil];
return p;
}
@end
答案 2 :(得分:1)
如果您使用locationInView:
而不是translationInView:
,您将获得绝对坐标而不是相对坐标。但是你必须启动平移以获得输入...要解决此问题,您的视图可以是UIButton,您可以触发与- (IBAction)buttonWasTouched:(UIButton *)button forEvent:(UIEvent *)event
连接的"touch down"
,如下所示:
-(IBAction)shakeIntensityPanGesturebuttonWasTouched:(UIButton *)button forEvent:(UIEvent *)event
{
UITouch *touch = [[event allTouches] anyObject];
CGPoint location = [touch locationInView:touch.view]; //touch location local cordinates
}
答案 3 :(得分:0)
您可以使用UIGestureRecognizerState
- (void) onPanGesture:(UIPanGestureRecognizer *)sender {
if(sender.state == UIGestureRecognizerStateBegan) {
origin = [sender locationInView];
} else {
current = [sender locationInView];
// Initial touch stored in origin
}
}
斯威夫特(ish):
var state = recognizer.state
if state == UIGestureRecognizerState.Began {
println(recognizer.locationInView(viewForGesture))
//this will be the point of first touch
}