2

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;
}

4 Answers 4

7

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];
 }
Sign up to request clarification or add additional context in comments.

4 Comments

But the function "touchesBegan" or "touchesMoved" are never called when my scrollview is scrolled. And I want to get the touch when my scrollview is used.
Even though "touchesBegan" is empty, her are never called.
Sorry try the above code. other method is yu need to call the sub classes . For further details, check out this link iosdevelopertips.com/user-interface/…
To detect touchesBegan and touchesMoved, sub-classing is NOT required. You can add the UIScrollViewDelegate to the "h" file and applicable functions to detect touches based on user intention. See stackoverflow.com/questions/993280/…
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.

Comments

2

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.

1 Comment

Thx! My code : '- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event{ self.position = point; return self; }'
1
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.