我有几个UIButton的视图。我使用UILongPressGestureRecognizer成功实现了以下作为选择器;
- (void)longPress:(UILongPressGestureRecognizer*)gesture {
if ( gesture.state == UIGestureRecognizerStateEnded ) {
NSLog(@"Long Press");
}
}
在这种方法中我需要知道的是UIButton接受了长按,因为我需要做一些不同的事情,这取决于哪个按钮接受了长按。
希望答案不是将长按发生的位置的坐标映射到按钮边界的问题 - 而不是去那里。
有什么建议吗?
谢谢!
答案 0 :(得分:12)
这可以在gesture.view
中找到。
答案 1 :(得分:3)
您是否将长按手势控制器添加到将UIButtons作为子视图的UIView?如果是这样的话,那么@Magic Bullet Dave的方法可能就好了。
另一种方法是子类化UIButton并向每个UIButton添加longTapGestureRecogniser。然后,您可以按下按钮来执行您喜欢的操作。例如,它可以向视图控制器发送标识自身的消息。以下代码段说明了子类的方法。
- (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.
}
答案 2 :(得分:1)
如果您的视图包含多个子视图(如许多按钮),您可以确定点击的内容:
// 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]])