Sunday, January 24, 2016

Objective C long press event

Sometimes, we need long press event, especially in games rather than just a tap or touch event.

For example, I need to change the template in an application on tapping the template icon and this change should be only a local change. If I need to change the template and also need to save the template ID in the server, Obviously I need another event on the template icon. 

One way is to write double tap event on that control, Which is not very handy. Another best approach is a long press event which users also feel very handy. Single tap local change and long press gives local as well as server change. In the usability point of view also this is a very good approach.


Let's see how to write a long press event on a control (UIButton, UILabel..) in Objective-C.

Like UITapGestureRecognizer, we have UILongPressGestureRecognizer in Objective C. Let's see how to apply this to a control.

I have a label and I need to apply long press on it.

UILabel *lbl = [UILabel alloc] init];
   [lbl seTextColor:[UIColor whiteColor]];

As it is a static control, by default it's user interaction is disabled. We need to explicitly enable it. Otherwise, these labels won't respond to these recognizers.

[lbl setUserInteractionEnabled:YES];

  UILongPressGestureRecognizer *longPress =       
                           [[UILongPressGestureRecognizer allocinitWithTarget:self 

  [longPress setMinimumPressDuration:3];

  longPress.delegate = (id <UIGestureRecognizerDelegate>)self;

  [lbl addGestureRecognizer:longPress];

I have added a long press gesture recognizer to the label. We can also set the minimum duration that user has to tap and hold on the control for this event. Unlike, tap events, these long press recognizers have states. Below are the UIGestureRecognizerState types.

    UIGestureRecognizerStateRecognized = UIGestureRecognizerStateEnded

Here, we are concerned about only 2 states. 

- (void) longPressEvent:(UILongPressGestureRecognizer*)gesture{
    if (gesture.state == UIGestureRecognizerStateBegan ) {        
        [self.titleLabel setTextColor:[UIColor redColor]];
    else if ( gesture.state == UIGestureRecognizerStateEnded) {

        self.titleLabel.textColor = [UIColor whiteColor]

First one is UIGestureRecognizerStateBegan. This where you can confirm like long press is happening on the control. Here I am just changing the color of the label text control to highlight it.

Second one is, UIGestureRecognizerStateEnded. This is where you can confirm like user has stopped the long press on the control. Here I am rolling back the label's actual text color.


Hope this post is useful. Feel free to comment incase of any queries.