7

我正在为 iPhone 编写一个 Objective-C 程序。

我正在尝试实现 aUILongPressGestureRecognizer并且无法让它按照我想要的方式运行。

想做的很简单:

响应在屏幕上按住的触摸。

每当触摸移动和触摸开始时,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];
4

1 回答 1

12

您描述的行为,当您不移动时,您的手势识别器不会收到对您的处理程序的进一步调用是标准行为。state当你移动时这些手势的属性是 type UIGestureRecognizerStateChanged,所以如果事情没有改变,你的处理程序就不会被调用是有道理的。

你可以

  • 在调用您的手势识别器stateUIGestureRecognizerStateBegan启动一个重复计时器;
  • state使用of UIGestureRecognizerStateCancelledUIGestureRecognizerStateFailedUIGestureRecognizerStateEndedthen调用您的手势识别invalidate器并释放计时器;
  • 确保手势识别器方法保存了您在某个类属性中寻找的任何值(例如,值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
于 2013-02-01T03:54:35.967 回答