按下时会两次调用UILongPressGestureRecognizer

我正在检测用户是否已按下2秒钟:


UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc]

                                             initWithTarget:self 

                                             action:@selector(handleLongPress:)];

        longPress.minimumPressDuration = 2.0;

        [self addGestureRecognizer:longPress];

        [longPress release];

这是我处理长按的方式:


-(void)handleLongPress:(UILongPressGestureRecognizer*)recognizer{

    NSLog(@"double oo");

}

当我按下2秒钟以上时,文本“ double oo”被打印两次。为什么是这样?我该如何解决?


PIPIONE
浏览 522回答 3
3回答

白衣非少年

UILongPressGestureRecognizer是连续事件识别器。您必须查看状态以查看这是事件的开始,中间还是结束,并采取相应的措施。即,您可以在开始之后放弃所有事件,或者仅根据需要查看运动。从 类参考:长按手势是连续的。当在指定时间段内(minimumPressDuration)按下了允许的手指数(numberOfTouchesRequired),并且触摸没有移动超出允许的移动范围(allowableMovement)时,手势即开始(UIGestureRecognizerStateBegan)。每当手指移动时,手势识别器都会转换为“更改”状态,并且在任何手指抬起时手势识别器都会终止(UIGestureRecognizerStateEnded)。现在您可以像这样跟踪状态-  (void)handleLongPress:(UILongPressGestureRecognizer*)sender {     if (sender.state == UIGestureRecognizerStateEnded) {      NSLog(@"UIGestureRecognizerStateEnded");    //Do Whatever You want on End of Gesture     }    else if (sender.state == UIGestureRecognizerStateBegan){       NSLog(@"UIGestureRecognizerStateBegan.");   //Do Whatever You want on Began of Gesture     }  }

鸿蒙传说

要检查UILongPressGestureRecognizer的状态,只需在选择器方法上添加if语句:- (void)handleLongPress:(UILongPressGestureRecognizer *)sender {        if (sender.state == UIGestureRecognizerStateEnded) {        NSLog(@"Long press Ended");    } else if (sender.state == UIGestureRecognizerStateBegan) {        NSLog(@"Long press detected.");    }}

撒科打诨

您需要检查正确的状态,因为每种状态都有不同的行为。您最有可能需要UIGestureRecognizerStateBegan带有状态UILongPressGestureRecognizer。UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc]                                             initWithTarget:self                                              action:@selector(handleLongPress:)];longPress.minimumPressDuration = 1.0;[myView addGestureRecognizer:longPress];[longPress release];...- (void)handleLongPress:(UILongPressGestureRecognizer *)gesture {    if(UIGestureRecognizerStateBegan == gesture.state) {        // Called on start of gesture, do work here    }    if(UIGestureRecognizerStateChanged == gesture.state) {        // Do repeated work here (repeats continuously) while finger is down    }    if(UIGestureRecognizerStateEnded == gesture.state) {        // Do end work here when finger is lifted    }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

iOS