在UILongPressGestureRecognizer上,我该如何检测哪个对象生成事件?

我有几个UIButtons的观点。 我用UILongPressGestureRecognizer成功实现了以下select器;

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

在这个方法中我需要知道的是UIButton收到的是longpress,因为我需要做一些不同的事情,具体取决于哪个button收到longpress。

希望答案不是将longpress发生的位置坐标映射到button边界的某个问题 – 宁可不去那里。

有什么build议么?

谢谢!

这在gesture.view可用。

您是否将长按手势控制器添加到具有UIButtons作为子视图的UIView? 如果是这样的话,那么@Magic Bullet Dave的方法可能就是要走的路。

另一种方法是inheritanceUIButton并向每个UIButton添加一个longTapGestureRecogniser。 然后你可以让你的button做你喜欢的。 例如,它可以向视图控制器发送标识自己的消息。 以下片段说明了子类的方法。

 - (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]; } } 

在你的视图控制器,你可能有这样的代码:

 - (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. } 

如果你的视图包含多个子视图(像很多button),你可以确定被点击的是什么:

 // 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]])