好了,我遇到了一个(对我来说)非常奇怪的问题。我在我的视图中有一个1500x150按钮,我已经添加了一个UILongPressGestureRecognizer
到那个按钮,因为我需要得到按钮被按下时被按下的点。我的代码看起来像这样:
-(CGPoint)detectedTouch:(UILongPressGestureRecognizer *)sender {
CGPoint touchPoint = [sender locationInView:button];
return touchPoint;
}
-(void)myAction {
CGPoint touchPoint = [self detectedTouch:myGestureRecognizer];
NSLog(@"touchPoint = %f, %f", touchPoint.x, touchPoint.y);
//do stuff
}
现在一切工作正常,当按钮是在一个正常的视图。但是当按钮在scrollView上时,它只会在你按下它一秒钟的时候起作用。如果你释放得太快,日志会显示如下:
touchPoint = nan, nan
任何帮助解决这个问题将非常感谢!
UIGestureRecognizer
在其生命周期中具有可能、已识别、失败、已结束、已取消等多种状态。我会尝试在状态的识别器方法中放入一个switch语句,看看哪种情况会更好地缩小问题范围。它看起来像这样:
switch (sender.state){
case UIGestureRecognizerStatePossible:
NSLog(@"possible");
break;
case UIGestureRecognizerStateFailed:
NSLog(@"Failed!");
break;
... All Cases wanted
default:
break;
}
我不知道内部细节,但也许如果它失败/取消,它不会在视图中拾取位置。
这里是关于子类化手势识别器和可能发生的状态的文档。
http://developer.apple.com/library/IOs/文档/UIKit/引用/UIGestureRecognizer_Class/引用/Reference.html
我试图重现您的问题,但没有成功。起初,我认为手势识别器可能会干扰scrollView滚动手势识别器,但情况似乎并非如此。下面是我的代码:
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
UILongPressGestureRecognizer *recognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleLongHold:)];
// [scrollView addGestureRecognizer:recognizer];
UILabel *lbl = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 2000)];
lbl.text = @"lorem ipsum......";
lbl.numberOfLines = 0;
scrollView.contentSize = CGSizeMake(lbl.frame.size.width, lbl.frame.size.height);
[scrollView addSubview:lbl];
btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
btn.frame = CGRectMake(0, 0, 150, 150);
[btn addGestureRecognizer:recognizer];
[scrollView addSubview:btn];
v = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 50, 50)];
v.backgroundColor = [UIColor yellowColor];
v.hidden = YES;
[scrollView addSubview:v];
}
- (void) handleLongHold:(UILongPressGestureRecognizer*) recognizer {
NSLog(@"long tap handled");
v.hidden = NO;
v.center = [recognizer locationInView:btn];
}
顺便说一下,我偶然发现你的问题寻找一种方法来找到一个触摸点从手势识别器选择器- locationInView方法帮助了我,希望这段代码帮助你。