Ayesha Fatima
Ayesha Fatima

Reputation: 367

Calculate UIButton Pressed Duration

Based on duration of UIButton Pressed, the same Buttton has to perform different tasks.

How to calculate duration of UIButton pressed?

Upvotes: 0

Views: 303

Answers (2)

joern
joern

Reputation: 27620

Us can set 2 actions to your button and measure the time that passes between these 2 methods are called:

UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
btn.frame = CGRectMake(100.0, 100.0, 100.0, 20.0);
[btn setTitle:@"Test" forState:UIControlStateNormal];
[btn addTarget:self action:@selector(userEndsTap:) forControlEvents:UIControlEventTouchUpInside];
[btn addTarget:self action:@selector(userStartsTap:) forControlEvents:UIControlEventTouchDown];

and in the two methods that get called you can do your duration measurement:

- (void)userEndsTap:(id)sender {
   NSLog(@"user ends tap");
   // stop measurement an do something different for different durations
}

- (void)userStartsTap:(id)sender {
   NSLog(@"user starts tap");
   // start measurement
}

Upvotes: 0

sergio
sergio

Reputation: 69027

Attach a UILongPressGestureRecognizer to your button and set the minimumPressDuration property. You can attach multiple gesture recognizers to the same button for different minimal press duration.

If you have "conflicts" between different gesture recognizers, you can settle them with –requireGestureRecognizerToFail: to specify that a gesture will only be recognized if another one is not.

Have a look at the relevant document.

Upvotes: 1

Related Questions