我在两个不同的位置有两个标签,当同时点击两个标签时,我希望另一个标签显示成功消息。
我如何做到这一点?我可以通过一个或多个手指触摸来识别单击或双击,但这是一种不同的情况。请帮忙。我尝试过这个,但它不起作用。
UITapGestureRecognizer *tapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap:)];
tapRecognizer.numberOfTapsRequired = 1;
tapRecognizer.numberOfTouchesRequired = 2;
tapRecognizer.delegate = self;
[self.view addGestureRecognizer:tapRecognizer];
-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
if (touch.view == tap2 && touch.view == tap1)
{
result.text = @"success";
}
return YES;
}
提前致谢。
答案 0 :(得分:2)
你想要检测的并不是一个单独的手势。
我建议为每个按钮添加一个点击手势识别器。处理程序将:
在真实设备上播放时间间隔以找到理想的数量。
更新:
显然未经过任何方式测试的代码段:
- (void)handleButton1Tap:(UITapGestureRecognizer *)sender {
if (sender.state == UIGestureRecognizerStateEnded)
{
self.button1TapTime = CACurrentMediaTime();
[self testForSimultaneousTap];
}
}
- (void)handleButton2Tap:(UITapGestureRecognizer *)sender {
if (sender.state == UIGestureRecognizerStateEnded)
{
self.button2TapTime = CACurrentMediaTime();
[self testForSimultaneousTap];
}
}
- (void)testForSimultaneousTap
{
if (fabs(self.button1TapTime - self.button2TapTime) <= 0.2)
{
// Do stuff
}
}
其中self.button1TapTime和self.button2TapTime是成员变量(双精度)。
添
答案 1 :(得分:0)
在形式上,我首先接受了termes的答案,这也有效,但我找到了一个更简单的解决方案。不需要两个手势识别器,可以通过简单的轻敲手势识别器实现,其中触摸次数计为两次。这是代码:
UITapGestureRecognizer *tapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap:)];
tapRecognizer.numberOfTapsRequired = 1;
tapRecognizer.numberOfTouchesRequired = 2;
tapRecognizer.delegate = self;
[self addGestureRecognizer:tapRecognizer];
现在,在手柄点击方法中,我们可以通过“locationOfTouch:inView:”轻松获得两个触摸点,这是UIGestureRecognizer类的实例方法。因此,在handleTap:
方法中,我们需要检查两个触点是否位于所需位置。这是代码:
-(void)handleTap:(UITapGestureRecognizer*)recognizer
{
if (recognizer.state == UIGestureRecognizerStateEnded)
{
CGPoint point1 = [recognizer locationOfTouch:0 self];
CGPoint point2 = [recognizer locationOfTouch:1 self];
if ([self validateTapIn:point1 and:point2])
{
resultLabel.text = @"success";
}
}
}
-(BOOL)validateTapIn:(CGPoint)point1 and:(CGPoint)point2
{
return
(CGRectContainsPoint(label1.frame, point1) && CGRectContainsPoint(label2.frame,:point2)) ||
(CGRectContainsPoint(label1.frame, point2) && CGRectContainsPoint(label2.frame, point1));
}