【问题标题】:UILongPressGestureRecognizer iOS for continuous actionUILongPressGestureRecognizer iOS 用于连续动作
【发布时间】:2015-12-11 18:48:13
【问题描述】:

我有一个按钮,我想“按住”按钮,这样它就会一直打印“长按”,直到我松开按键。

我在 ViewDidLoad 中有这个:

[self.btn addTarget:self action:@selector(longPress:) forControlEvents:UIControlEventTouchDown];

- (void)longPress: (UILongPressGestureRecognizer *)sender {
    if (sender.state == UIControlEventTouchDown) {
      NSLog(@"Long Press!");
    }
}

我也试过这个:

 UILongPressGestureRecognizer *lpgr = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(longPress:)];
 lpgr.minimumPressDuration = 0.1;
 lpgr.numberOfTouchesRequired = 1;
 [self.btn addGestureRecognizer:lpgr];

它只打印长按!即使我按住按钮一次。 谁能告诉我哪里做错了或者我错过了什么? 谢谢!

【问题讨论】:

  • 请勿将代码发布为图片。将代码复制并粘贴到您的问题中。然后确保你的格式正确。
  • 那么,会发生什么?是否调用了您的 handleLongPressGesture 方法?
  • 如果我删除“if ([sender isEqual: self.lpgr])”就会被调用,但它只会向后删除一次。
  • 我不确定,但请尝试增加最短新闻持续时间....只是一种解决方法

标签: ios xcode gesture uilongpressgesturerecogni


【解决方案1】:

首先,UIButton的目标-动作对回调仅在相应事件触发时执行一次

UILongPressGestureRecognizer需要一个minimumPressDuration才能进入UIGestureRecognizerStateBegan状态,然后当手指移动时,回调会触发UIGestureRecognizerStateChanged 状态。最后,UIGestureRecognizerStateEnded 释放手指时的状态。

按下按钮时,您的要求会反复触发。一流的都不能满足您的需求。相反,您需要在按钮按下时设置重复触发计时器,并在按钮松开时释放它。

所以代码应该是:

    [btn addTarget:self action:@selector(touchBegin:) forControlEvents: UIControlEventTouchDown];
    [btn addTarget:self action:@selector(touchEnd:) forControlEvents:
        UIControlEventTouchUpInside | UIControlEventTouchUpOutside | UIControlEventTouchCancel];

- (void)touchBegin:(UIButton*)sender {
    _timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(longPress:) userInfo:nil repeats:YES];
}

- (void)touchEnd:(UIButton*)sender {
    [_timer invalidate];
    _timer = nil;
}

- (void)longPress:(NSTimer*)timer {
    NSLog(@"Long Press!");
}

顺便说一下,UIButtonUILongPressGestureRecognizer 都没有 UIControlEvents

类型的状态

【讨论】:

  • 但这只会打印出长按! 0.1 秒长。如果我想继续打印直到触摸结束,我应该在 TimeInterval 中输入什么?
  • @CathyOun 你可以更改间隔
猜你喜欢
  • 2014-06-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-06
  • 2019-02-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多