【问题标题】:Multiple Gesture Responders for a Single View单个视图的多个手势响应器
【发布时间】:2012-01-05 17:29:07
【问题描述】:
我想设置一个图像来响应几个不同的手势响应器。因此,例如,如果触摸了图片的一部分,我希望调用一个选择器,并为图片的不同部分调用另一个选择器。
我查看了UIGestureRecognizer 和UITapGestureRecognizer 类,但找不到指定要与它们关联的图像区域的方法。这在iOS中完全可能吗?如果是这样,我应该考虑使用哪些类?
【问题讨论】:
标签:
ios
cocoa-touch
uigesturerecognizer
uitapgesturerecognizer
【解决方案1】:
最简单的解决方案是在图像上放置不可见的视图并在其上放置手势识别器。
如果这不可行,您将不得不查看手势识别器的点击处理程序中的 locationInView,并根据用户点击的位置确定您想要做什么。
【解决方案2】:
使用locationInView: 属性确定点击发生的位置,然后有条件地调用方法。您可以通过设置一些与您的命中区域相对应的CGRects 来做到这一点。然后使用CGRectContainsPoint() 函数确定点击是否落在了某个命中区域。
您的点击手势识别器操作可能如下所示:
- (void)tapGestureRecognized:(UIGestureRecognizer *)recognizer
{
// Specify some CGRects that will be hit areas
CGRect firstHitArea = CGRectMake(10.0f, 10.0f, 44.0f, 44.0f);
CGRect secondHitArea = CGRectMake(64.0f, 10.0f, 44.0f, 44.0f)
// Get the location of the touch in the view's coordinate space
CGPoint touchLocation = [recognizer locationInView:recognizer.view];
if (CGRectContainsPoint(firstHitArea, touchLocation))
{
[self firstMethod];
}
else if (CGRectContainsPoint(secondHitArea, touchLocation))
{
[self secondMethod];
}
}