通过UIGestureRecognizer同时处理两个不同点的点击 [英] handle taps in two different points at a same time via UIGestureRecognizer
问题描述
我在两个不同的位置有两个标签,当两个标签同时被点击时,我希望另一个标签显示成功消息。
I have two labels in two different positions, when both labels are tapped at the same time i want another label to show a success message.
我如何做到这一点?我可以通过一次或多次手指触摸来识别单击或双击,但这是一种不同的情况。请帮忙。我尝试了这个,但它不起作用。
How do I accomplish this? I can recognize a single tap or double tap with one or more finger touches but this is a different scenario. Please help. I tried this, but it does not work.
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;
}
提前致谢。
推荐答案
我正式接受了termes的回答并且也有效,但我找到了一个更简单的解决方案。不需要两个手势识别器,可以通过简单的轻击手势识别器实现,其中触摸次数计为两次。以下是代码:
Formally I had accepted termes's answer first and that worked too, but I have found a more simpler solution to this process. There is no need for two gesture recognizers, it is achievable with a simple tap gesture recognizer with number of touches count to two. Here is the code:
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:
方法中,我们需要检查两个触点是否在所需位置。以下是代码:
Now, in the handle tap method we can easily get the two touch points by "locationOfTouch:inView:", a instance method of UIGestureRecognizer class. So in the handleTap:
method we need to check if the two touch points are in the desired location. Here is the code:
-(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));
}
这篇关于通过UIGestureRecognizer同时处理两个不同点的点击的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!