UIScrollview 获取触摸事件

如何检测 UIScrollView中的接触点? 接触委托方法不起作用。

51469 次浏览

如果我们讨论的是 scrollview 中的点,那么你可以使用 Committee 方法:

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView

在方法内部,读取属性:

@property(nonatomic) CGPoint contentOffset

从 scrollView 获取协调。

设置一个点击手势识别器:

UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(singleTapGestureCaptured:)];
[scrollView addGestureRecognizer:singleTap];

然后你就可以接触到:

- (void)singleTapGestureCaptured:(UITapGestureRecognizer *)gesture
{
CGPoint touchPoint=[gesture locationInView:scrollView];
}

您可以创建自己的 UIScrollview 子类,然后可以实现以下内容:

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event


{


NSLog(@"DEBUG: Touches began" );


UITouch *touch = [[event allTouches] anyObject];


[super touchesBegan:touches withEvent:event];
}


- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event {


NSLog(@"DEBUG: Touches cancelled");


// Will be called if something happens - like the phone rings


UITouch *touch = [[event allTouches] anyObject];


[super touchesCancelled:touches withEvent:event];


}




- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {


NSLog(@"DEBUG: Touches moved" );


UITouch *touch = [[event allTouches] anyObject];


[super touchesMoved:touches withEvent:event];


}


- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
NSLog(@"DEBUG: Touches ending" );
//Get all the touches.
NSSet *allTouches = [event allTouches];


//Number of touches on the screen
switch ([allTouches count])
{
case 1:
{
//Get the first touch.
UITouch *touch = [[allTouches allObjects] objectAtIndex:0];


switch([touch tapCount])
{
case 1://Single tap


break;
case 2://Double tap.


break;
}
}
break;
}
[super touchesEnded:touches withEvent:event];
}

这也适用于触地事件。

在当前正确标记的 回答中,只有在“点击”事件中才能得到 touch point。这个事件似乎只在“竖起手指”时发生,而不是在下面。

从相同答案中 yuf 的注释中,你可以从 UIScrollView中的基础视图中得到 touch point

- (BOOL)gestureRecognizer:(UIGestureRecognizer*)gestureRecognizer shouldReceiveTouch:(UITouch*)touch
{
CGPoint touchPoint = [touch locationInView:self.view];


return TRUE; // since we're only interested in the touchPoint
}

根据苹果的 文件gestureRecognizer的功能是:

询问委托手势识别器是否应该接收表示触摸的对象。

对我来说,这意味着我可以决定 gestureRecognizer是否应该接受触摸。