Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Receive tap gestures only on part of a view

I have a UIImageView in a view controller. Is it possible to make certain areas of the image view tappable?

Example : I have an image of a map. Make only the POIs tappable. Not the whole image. Is this possible?

like image 446
Isuru Avatar asked Jun 26 '13 04:06

Isuru


3 Answers

Thanks to manujmv, I was able to figure out Swift 3 implementation of a Custom Gesture Area. In my case I'm creating 50 point strips on each side of the window to move from one VC to another. But it should be pretty easy to reuse this for any other application:

class ViewController: UIViewController {
   ...
   var mySensitiveArea: CGRect?
   ...
   override func viewDidLoad() {
   ...
   let screenWidth = UIScreen.main.bounds.size.width
   let screenHeight = UIScreen.main.bounds.size.height
   mySensitiveArea = CGRect(0, 0, 50, screenHeight)
   let swipeGesture = UISwipeGestureRecognizer(target: self, action: #selector(self.handleGesture(_:)))
   swipeGesture.direction = UISwipeGestureRecognizerDirection.right
   self.view.addGestureRecognizer(swipeGesture)
   }
}

//Function for determining when swipe gesture is in/outside of touchable area
func handleGesture(_ gestureRecognizer: UIGestureRecognizer) {
    let p = gestureRecognizer.location(in: self.view)
    if mySensitiveArea!.contains(p) {
        print("it's inside")
        showMainViewController()
    }
    else {
        print("it's outside")
    }
}

//Segue to Main VC
func showMainViewController() {
    self.performSegue(withIdentifier: "toMain", sender: self)
}
like image 90
Repose Avatar answered Nov 07 '22 20:11

Repose


You can use the handleGesture method. First you need to create a location to receive the touches and you have to compare it with touch location in the delegate method as below:

CGRect locationRect;

in viewdidload

locationRect = CGRectMake(CREATE A FRAME HERE);

next the delegate method

- (void)handleGesture:(UIGestureRecognizer *)gestureRecognizer {
    CGPoint p = [gestureRecognizer locationInView:self.view];
    if (CGRectContainsPoint(locationRect, p)) {
        NSLog(@"it's inside");
    } else {
        NSLog(@"it's outside");
    }
}
like image 18
manujmv Avatar answered Nov 07 '22 21:11

manujmv


Yes it is possible, but you should ask yourself whether or not it is worth it. If it were me, I would add a point of interest object onto the map and attach a gesture recognizer to that instead. However, if you want to go the other route you can look into the following method of UIGestureRecognizerDelegate

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch

This will say whether or not the gesture should process a given touch. You can filter it based on your POIs.

like image 2
borrrden Avatar answered Nov 07 '22 21:11

borrrden