2

In my project I have the need to use a UIButton (or another component) to handle events using long press. Let me explain, I should make that mind I hold down the button a timer to count the seconds and release to pressure stop, I tried with the management of UILongPressGestureRecognizer but is not the case because I recall the event when the button is held down but only if I move my finger, but I wish the timer went away and counted all the time in which the button is held down (with your finger stationary) and stopped counting when the finger is released.

Does anyone know how to help me? Thanks

AleMal
  • 1,977
  • 6
  • 24
  • 49
  • I cannot understand your question. Can you try saying it a different way? – rob mayoff Feb 22 '12 at 06:16
  • Hi i need to press a button and count for how mutch second i press it (for how mutch time my finger was on it), if i keep my finger on a button for five second a timer start and count 5 second and then i release button timer stop. – AleMal Feb 22 '12 at 06:29

2 Answers2

6

Use these two methods for buttons events. touchDown is called when you press the button and touchUp will be called when you lift your finger from the button. Calculate the time difference between these two methods. Also you can start timer in touchDown and stop/restart it in touchUp.

//connect this action with Touch up inside
- (IBAction)touchUp:(id)sender {
    NSLog(@"up");
}

//connect this to tocuh down
- (IBAction)touchDown:(id)sender{
    NSLog(@"down");
}

Updated In coding you can write like this

[btn addTarget:self action:@selector(touchUp:) forControlEvents:UIControlEventTouchUpInside];
[btn addTarget:self action:@selector(touchDown:) forControlEvents:UIControlEventTouchDown];

and in xib enter image description here

Inder Kumar Rathore
  • 39,458
  • 17
  • 135
  • 184
0

The same I have done...As u said about UILongPressGestureRecognizer, I can't understand it..but u can write ur code inside-(void)handleLongPress:(UILongPressGestureRecognizer *)gestureRecognizer { }. I have done same by using this method and got successful result..:). You even don't need to add timer,instead u can use...

 UILongPressGestureRecognizer *lpgr = [[UILongPressGestureRecognizer alloc] 
                                      initWithTarget:self action:@selector(handleLongPress:)];
lpgr.minimumPressDuration = 1.0;
lpgr.delegate = self;

I think this works perfectly..

Krunal
  • 1,318
  • 1
  • 13
  • 31
  • Thanks but it also works if I hold finger lock on the button? I tried using UILongPressGestureRecognizer but it worked only if I moved my finger – AleMal Feb 22 '12 at 07:10
  • It should work. Unless you have this button in a UIScrollView or you have anothe UIGestureRecognizer that is interfering with this one. – Rok Jarc Feb 22 '12 at 08:39