Ios – UILongPressGestureRecognizer Turns Off UIButton Highlighting

iosios4iphone

I have a UILongPressGestureRecognizer added to a UIButton. When I press the UIButton it gets highlighted as expected. However, when the UILongPressGestureRecognizer selector gets called the highlighting gets turned off.

    UILongPressGestureRecognizer *longpressGesture = 
     [[UILongPressGestureRecognizer alloc] initWithTarget:self
                                            action:@selector(longPressHandler:)];
    longpressGesture.minimumPressDuration = 5;
    [longpressGesture setDelegate:self];
    [self.myUIButton addGestureRecognizer:longpressGesture];
    [longpressGesture release];

    - (void)longPressHandler:(UILongPressGestureRecognizer *)gestureRecognizer {
    NSLog(@"longPressHandler");
}

In the above example, the selector gets called after 5 seconds of holding down the button. The button is highlighted prior to the selector being called, but then gets unhighlighted when the selector is called, even though I am still pressing the button.

Can anyone explain why this happens, and how it can be prevented? I would like the button to remain highlighted the entire time while pressed down. Thanks.

Best Answer

After further research, I discovered that this is due to the default behavior of Gesture Recognizers, which cancel touches in the hierarchy once they recognize a gesture. So, once the Gesture Recognizer recognizes a gesture, it cancels the touch to the UI Button, which then gets unhighlighted, since it no longer has a touch event.

This behavior can be changed using the cancelsTouchesInView property

longpressGesture.cancelsTouchesInView = NO;

Setting this to NO will pass the touch through to the responder chain.

Related Topic