0

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.

I have this in the 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!

Cathy Oun
  • 315
  • 2
  • 11

1 Answers1

2

First, UIButton's target-action pair callback only execute once when correspond events fire.

The UILongPressGestureRecognizer need to a minimumPressDuration to get into UIGestureRecognizerStateBegan state, then when finger move, callback will fire with UIGestureRecognizerStateChanged state. At last, UIGestureRecognizerStateEnded state when release finger.

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

SolaWing
  • 1,652
  • 12
  • 14