VivienCormier
VivienCormier

Reputation: 1133

Detect touch position on UiScrollView

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

Upvotes: 2

Views: 7915

Answers (4)

Łukasz Gierałtowski
Łukasz Gierałtowski

Reputation: 607

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.

Upvotes: 1

rounak
rounak

Reputation: 9387

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.

Upvotes: 3

thxou
thxou

Reputation: 691

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.

Upvotes: 2

iVenky
iVenky

Reputation: 441

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

Upvotes: 7

Related Questions