Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

On a UILongPressGestureRecognizer how do I detect which object generated the event?

I have a view with several UIButtons. I have successfully implemented using UILongPressGestureRecognizer with the following as the selector;

- (void)longPress:(UILongPressGestureRecognizer*)gesture {
    if ( gesture.state == UIGestureRecognizerStateEnded ) {
        NSLog(@"Long Press");
    }
}

What I need to know within this method is which UIButton received the longpress since I need to do something different, depending on which button received the longpress.

Hopefully the answer is not some issue of mapping the coordinates of where the longpress occured to the bounds of the buttons - would rather not go there.

Any suggestions?

Thanks!

like image 460
macgeezer Avatar asked Sep 09 '11 12:09

macgeezer


2 Answers

This is available in gesture.view.

like image 124
Rob Napier Avatar answered Oct 14 '22 19:10

Rob Napier


Are you adding the long tap gesture controller to the UIView that has the UIButtons as subviews? If so, something along the lines of @Magic Bullet Dave's approach is probably the way to go.

An alternative is to subclass UIButton and add to each UIButton a longTapGestureRecogniser. You can then get your button to do what you like. For example, it could send a message identifying itself to a view controller. The following snippet illustrates methods for the subclass.

- (void) setupLongPressForTarget: (id) target;
{
    [self setTarget: target];  // property used to hold target (add @property and @synthesise as appropriate)

    UILongPressGestureRecognizer* longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:button action:@selector(longPress:)];
    [self addGestureRecognizer:longPress];
    [longPress release];
}

- (void) longPress: (UIGestureRecognizer*) recogniser;
{
    if (![recogniser isEnabled]) return; // code to prevent multiple long press messages
    [recogniser setEnabled:NO];
    [recogniser performSelector:@selector(setEnabled:) withObject: [NSNumber numberWithBool:YES] afterDelay:0.2];

    NSLog(@"long press detected on button"); 

    if ([[self target] respondsToSelector:@selector(longPressOnButton:)])
    {
        [[self target] longPressOnButton: self];
    }
}

In your view controller you might have code something like this:

- (void) viewDidLoad;
{
    // set up buttons (if not already done in Interface Builder)

    [buttonA setupLongPressForTarget: self];
    [buttonB setupLongPressForTarget: self];

    // finish any other set up
}

- (void) longPressOnButton: (id) sender;
{
     if (sender = [self buttonA])
     {
         // handle button A long press
     }

    if (sender = [self buttonB])
     {
         // handle button B long press
     }

     // etc.

 }
like image 29
Obliquely Avatar answered Oct 14 '22 19:10

Obliquely