UILongPressGestureRecognizer不会响应触摸和保持

J-R*_*ock 7 cocoa-touch objective-c uigesturerecognizer ios

我正在为iPhone编写Objective-C程序.

我正在尝试实现一个UILongPressGestureRecognizer并且不能让它按照我想要的方式运行.

想做的很简单:

响应触摸被保持下来在屏幕上.

UILongPressGestureRecognizer作品就好每当移动触摸屏当触摸开始,但如果我按住在同一个地方的联系,没有任何反应.

为什么?

我怎样才能处理触摸开始,而不是移动,并保持在完全相同的位置?

这是我目前的代码.


// Configure the press and hold gesture recognizer 
touchAndHoldRecognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(touchAndHold:)]; 
touchAndHoldRecognizer.minimumPressDuration = 0.1; 
touchAndHoldRecognizer.allowableMovement = 600;
[self.view addGestureRecognizer:touchAndHoldRecognizer];
Run Code Online (Sandbox Code Playgroud)

Rob*_*Rob 12

您描述的行为是您的手势识别器在您不移动时未接收到对您的处理程序的进一步调用的行为是标准行为.state移动时这些手势的属性属于类型UIGestureRecognizerStateChanged,因此如果事情没有改变,则不会调用您的处理程序.

你可以

  • 当调用你的手势识别用stateUIGestureRecognizerStateBegan启动重复的计时器;
  • 在通话与您的手势识别stateUIGestureRecognizerStateCancelled,UIGestureRecognizerStateFailedUIGestureRecognizerStateEndedinvalidate并释放定时器;
  • 确保手势识别器方法在某些类属性中保存您正在寻找的任何值(例如,值locationInView或其他值)

所以,也许是这样的:

@interface ViewController ()

@property (nonatomic) CGPoint location;
@property (nonatomic, strong) NSTimer *timer;

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

    UILongPressGestureRecognizer *gesture = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleGesture:)];
    gesture.minimumPressDuration = 0.1;
    gesture.allowableMovement = 600;
    [self.view addGestureRecognizer:gesture];
}

- (void)handleTimer:(NSTimer *)timer
{
    [self someMethod:self.location];
}

- (void)handleGesture:(UIGestureRecognizer *)gesture
{
    self.location = [gesture locationInView:self.view];

    if (gesture.state == UIGestureRecognizerStateBegan)
    {
        self.timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(handleTimer:) userInfo:nil repeats:YES];
    }
    else if (gesture.state == UIGestureRecognizerStateCancelled ||
             gesture.state == UIGestureRecognizerStateFailed ||
             gesture.state == UIGestureRecognizerStateEnded)
    {
        [self.timer invalidate];
        self.timer = nil;
    }

    [self someMethod:self.location];
}

- (void)someMethod:(CGPoint)location
{
    // move whatever you wanted to do in the gesture handler here.

    NSLog(@"%s", __FUNCTION__);
}

@end
Run Code Online (Sandbox Code Playgroud)