ios – UILongPressGestureRecognizer不会响应touch&HOLD

我正在为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];

解决方法

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

你可以

>在调用UIGestureRecognizerStateBegan状态的手势识别器时,启动重复计时器;
>在调用状态为UIGestureRecognizerStateCancelled,UIGestureRecognizerStateFailed或UIGestureRecognizerStateEnded的手势识别器时,然后使计时器无效并释放;
>确保手势识别器方法在某些类属性中保存您正在查找的任何值(例如,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

相关文章

UITabBarController 是 iOS 中用于管理和显示选项卡界面的一...
UITableView的重用机制避免了频繁创建和销毁单元格的开销,使...
Objective-C中,类的实例变量(instance variables)和属性(...
从内存管理的角度来看,block可以作为方法的传入参数是因为b...
WKWebView 是 iOS 开发中用于显示网页内容的组件,它是在 iO...
OC中常用的多线程编程技术: 1. NSThread NSThread是Objecti...