为了账号安全,请及时绑定邮箱和手机立即绑定

按下时会两次调用UILongPressGestureRecognizer

按下时会两次调用UILongPressGestureRecognizer

iOS
PIPIONE 2019-12-06 06:06:44
我正在检测用户是否已按下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”被打印两次。为什么是这样?我该如何解决?
查看完整描述

3 回答

?
白衣非少年

TA贡献1155条经验 获得超0个赞

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

     }

  }



查看完整回答
反对 回复 2019-12-07
?
鸿蒙传说

TA贡献1865条经验 获得超7个赞

要检查UILongPressGestureRecognizer的状态,只需在选择器方法上添加if语句:


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

    if (sender.state == UIGestureRecognizerStateEnded) {

        NSLog(@"Long press Ended");

    } else if (sender.state == UIGestureRecognizerStateBegan) {

        NSLog(@"Long press detected.");

    }

}



查看完整回答
反对 回复 2019-12-07
?
撒科打诨

TA贡献1934条经验 获得超2个赞

您需要检查正确的状态,因为每种状态都有不同的行为。您最有可能需要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

    }

}



查看完整回答
反对 回复 2019-12-07
  • 3 回答
  • 0 关注
  • 521 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信