[英]UITapGestureRecognizer on a UIButton
我有一个UIButton,它有一个IBAction和一个UITapGestureRecognizer来检测双击。
目前,看起来IBAction正在阻止识别器。 有没有办法阻止这个或UITapGestureRecognizer甚至工作按钮? 如果是这样,只是添加识别器并删除IBActions是不是更好?
编辑
UITapGestureRecognizer *doubleTap = [[UITapGestureRecognizer alloc] initWithTarget : self action : @selector (handleDoubleTap:)];
[doubleTap setNumberOfTapsRequired:2];
[A1 addGestureRecognizer:doubleTap];
[A2 addGestureRecognizer:doubleTap];
[B1 addGestureRecognizer:doubleTap];
看起来您正在尝试将一个手势识别器附加到多个按钮。 手势识别器一次只能附加到一个视图。 因此,在您的情况下,您将识别器附加到(按钮B1)的最后一个按钮可能响应双击,但A1和A2不响应。
为每个按钮创建一个单独的识别器。
但是所有三个识别器都可以调用相同的操作方法( handleDoubleTap:
。
但是,当您尝试单击某个按钮时,会有轻微的延迟,因为它等待查看它是否是双击的开始。 有一些方法可以减少延迟,但如果您能忍受延迟并且变通方法带来其他问题,则可能不值得。
编辑:
在你的评论中,你说你“想要检测它们是否同时被按下”。 为此,您不需要手势识别器。 您可以使用提供的标准控制事件。
接下来,在IB中,对于每个按钮,使用buttonPressed:
连接“Touch Down”事件buttonPressed:
。 或者,以编程方式执行:
[button1 addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchDown];
[button2 addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchDown];
[button3 addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchDown];
接下来,在IB中,对于每个按钮,使用buttonReleased:
连接“Touch Up Inside” 和 “Touch Up Outside”事件。 或者,以编程方式执行:
[button1 addTarget:self action:@selector(buttonReleased:) forControlEvents:UIControlEventTouchUpInside|UIControlEventTouchUpOutside];
[button2 addTarget:self action:@selector(buttonReleased:) forControlEvents:UIControlEventTouchUpInside|UIControlEventTouchUpOutside];
[button3 addTarget:self action:@selector(buttonReleased:) forControlEvents:UIControlEventTouchUpInside|UIControlEventTouchUpOutside];
接下来,添加ivars以跟踪按下的按钮数量或按钮:
@property (nonatomic) int numberOfButtonsBeingTouched;
@property (strong, nonatomic) NSMutableSet *buttonsBeingTouched; //alloc + init in viewDidLoad or similar
如果您只关心按下了多少个按钮,则不需要NSMutableSet
。
最后,添加buttonPressed和buttonReleased方法:
- (IBAction)buttonPressed:(UIButton *)button {
self.numberOfButtonsBeingTouched++;
[self.buttonsBeingTouched addObject:button];
//your logic here (if (self.numberOfButtonsBeingTouched == 3) ...)
}
- (IBAction)buttonReleased:(UIButton *)button {
self.numberOfButtonsBeingTouched--;
[self.buttonsBeingTouched removeObject:button];
//your logic (if any needed) here
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.