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

前端 未结 3 1919
醉梦人生
醉梦人生 2021-02-14 07:20

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

- (void)longPress:(         


        
相关标签:
3条回答
  • 2021-02-14 07:57

    This is available in gesture.view.

    0 讨论(0)
  • 2021-02-14 08:04

    If your view contains multiple subViews (like lots of buttons) you can determine what was tapped:

    // Get the position of the point tapped in the window co-ordinate system
    CGPoint tapPoint = [gesture locationInView:nil];
    
    UIView *viewAtBottomOfHeirachy = [self.window hitTest:tapPoint withEvent:nil];
    
    if ([viewAtBottomOfHeirachy isKindOfClass:[UIButton class]])
    
    0 讨论(0)
  • 2021-02-14 08:11

    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.
    
     }
    
    0 讨论(0)
提交回复
热议问题