简体   繁体   English

UILongPressGestureRecognizer iOS连续动作

[英]UILongPressGestureRecognizer iOS for continuous action

I have a button, and I want to "press down and hold" the button so it will keep printing "Long Press" until I release the key press. 我有一个按钮,我想“按下并按住”按钮,以便它将一直打印“ Long Press”,直到我释放按键为止。

I have this in the ViewDidLoad: 我在ViewDidLoad中有这个:

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

and

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

I have also tried this: 我也尝试过这个:

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

It only prints out Long Press! 它只打印出长按! once even when I hold down the button. 即使按下按钮一次也是如此。 Can anyone tell me where I did wrong or what I missed? 谁能告诉我我做错了什么或错过了什么? Thanks! 谢谢!

First, UIButton 's target-action pair callback only execute once when correspond events fire. 首先,当对应事件触发时, UIButton的target-action对回调仅执行一次

The UILongPressGestureRecognizer need to a minimumPressDuration to get into UIGestureRecognizerStateBegan state, then when finger move, callback will fire with UIGestureRecognizerStateChanged state. UILongPressGestureRecognizer需要达到MinimumPressDuration才能进入UIGestureRecognizerStateBegan状态,然后当手指移动时,回调将以UIGestureRecognizerStateChanged状态触发。 At last, UIGestureRecognizerStateEnded state when release finger. 最后,释放手指时, UIGestureRecognizerStateEnded状态。

Your requirement is repeatedly fire when button pressed down. 按下按钮时,您的要求会反复触发。 None of the top class satisfy your need. 顶级人士都不满足您的需求。 Instead, you need to set a repeat fire timer when button press down, and release it when button release up. 相反,您需要在按下按钮时设置一个重复触发计时器 ,并在释放按钮时将其释放。

so the code should be: 因此代码应为:

    [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!");
}

By the way, neither UIButton nor UILongPressGestureRecognizer have a state with type UIControlEvents 顺便说一句, UIButtonUILongPressGestureRecognizer都不具有UIControlEvents类型的状态

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM