Mariam
Mariam

Reputation: 713

UIScrollView detect user taps

I'm using UIScrollView with PagingEnabled, inside UIScrollView I added three UIImage. It's work fine.

I'm wondering how can I detect if the user taps between two squares in UIImage,for example: in the attached image how can I detect if the user taps between squares 1 and 2 or if the user taps between squares 2 and 3?

Any ideas?

Thanks.

enter image description here

Upvotes: 1

Views: 137

Answers (2)

falsecrypt
falsecrypt

Reputation: 1616

For detecting single or multiple taps use UITapGestureRecognizer, its a subclass of UIGestureRecognizer. You should not forget to set the userInteractionEnabled property to YES, because UIImageView- class changes the default value to NO.

self.imageView.userInteractionEnabled = YES;
UITapGestureRecognizer *tapRecognizer = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(handleTap:)];
// Set the number of taps, if needed
[tapRecognizer setNumberOfTouchesRequired:1];
// and add the recognizer to our imageView
[imageView addGestureRecognizer:tapRecognizer];

- (void)handleTap:(UITapGestureRecognizer *)sender {
    if (sender.state == UIGestureRecognizerStateEnded) {
        // if you want to know, if user tapped between two objects
        // you need to get the coordinates of the tap
        CGPoint point = [sender locationInView:self.imageView];
        // use the point
        NSLog(@"Tap detected, point: x = %f y = %f", point.x, point.y );
       // then you can do something like
       // assuming first square's coordinates: x: 20.f y: 20.f width = 10.f height: 10.f
       // Construct the frames manually
       CGRect firstSquareRect = CGRectMake(20.f, 20.f, 10.f, 10.f);
       CGRect secondSquareRect = CGRectMake(60.f, 10.f, 10.f, 10.f);
       if(CGRectContainsPoint(firstSquareRect, point) == NO && 
          CGRectContainsPoint(secondSquareRect, point) == NO && 
          point.y < (firstSquareRect.origin.y + firstSquareRect.size.height) /* the tap-position is above the second square */ ) {
         // User tapped between the two objects
       }
    }
}

Upvotes: 0

nivritgupta
nivritgupta

Reputation: 1966

Add Gestures to image view

imageView.userInteractionEnabled = YES;
UIPinchGestureRecognizer *pgr = [[UIPinchGestureRecognizer alloc] 
    initWithTarget:self action:@selector(handlePinch:)];
pgr.delegate = self;
[imageView addGestureRecognizer:pgr];
[pgr release];
:
:
- (void)handlePinch:(UIPinchGestureRecognizer *)pinchGestureRecognizer
{
  //handle pinch...
}

Upvotes: 1

Related Questions