-->

Detect touch position on UiScrollView

2020-07-26 11:44发布

问题:

I need to get the touch position from a UIScrollView. But when I create a subclass for my scrollview :

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
  NSArray *touchesArray = [touches allObjects];
  UITouch *touch = (UITouch *)[touchesArray objectAtIndex:0];
  CGPoint point = [touch locationInView:self];
  self.position = point;}

The function touchesBegan isn't always called. If I swipe fast, touchesBegan is never called, but scrollViewDidScroll gets directly called instead.

I can't use UIGesture (UITapGestureRecognizer, ... ) because users don't tap or swipe.

Are there others methods to get the position from UIScrollView ?

EDIT :

Thanks ThXou : https://stackoverflow.com/a/15763450/1752843

UIScrollView subclass :

- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event{
    self.position = point;
    return self;
}

回答1:

I saw an answer in SO that I think that it can solve you problem. It seems that the SDK doesn't pass the touch handling methods to the UIScrollView subclasses anymore. So, you should to perform a hitTest: to pass the touches to your subclass.

See the answer for more information.



回答2:

To detect the touch location inside scrollview, try this code

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

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


回答3:

You could alternatively use scrollview.panGestureRecognizer's locationInView method to get the coordinates of a touch in your view. This could be in any of scrollView's delegate method depending on your requirements.



回答4:

scrollView.delaysContentTouches = NO;

It will makes that touchesBegan and other touch events will be triggered before scrollViewDidScroll.

The hitTest is a hack and should not be preferred solution.