Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elegant way to implement press and hold continuous event firing?

I often have a need to fire a sequence of events as a result of holding down a button. Think of a + button that increments a field: tapping it should increment it by 1, but tap & hold should say increment this by 1 every second until the button is released. Another example is the scrubbing function when holding down the backwards or forwards button in an audio player type app.

I usually resort to the following strategy:

  1. On touchDownInside I set up a repeating timer with my desired interval.
  2. On touchUpInside I invalidate and release the timer.

But for every such button I need a separate timer instance variable, and 2 target-actions, and 2 method implementations. (This is assuming I'm writing a generic class and don't want to impose restrictions on the max number of simultaneous touches).

Is there a more elegant way to solve this that I'm missing?

like image 505
lmirosevic Avatar asked Oct 06 '22 02:10

lmirosevic


2 Answers

Register the events for every button by:

[button addTarget:self action:@selector(touchDown:withEvent:) forControlEvents:UIControlEventTouchDown];
[button addTarget:self action:@selector(touchUpInside:withEvent:) forControlEvents:UIControlEventTouchUpInside];

For each button, set the tag attribute:

button.tag = 1; // 2, 3, 4 ... etc

In the handler, do whatever you need. Identify a button by the tag:

- (IBAction) touchDown:(Button *)button withEvent:(UIEvent *) event
{
     NSLog("%d", button.tag);
}
like image 135
ohho Avatar answered Oct 10 '22 02:10

ohho


I suggest UILongPressGestureRecognizer.

UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(addOpenInService:)];
    longPress.delegate      =   self;
    longPress.minimumPressDuration = 0.7;
    [aView addGestureRecognizer:longPress];
    [longPress release];
    longPress = nil;

On firing the event, you can get the call in

- (void) addOpenInService: (UILongPressGestureRecognizer *) objRecognizer
{
    // Do Something
}

Likewise you can use UITapGestureRecognizer for recognizing user taps.

Hope this helps. :)

like image 35
Mathew Varghese Avatar answered Oct 10 '22 04:10

Mathew Varghese