-1

Good day, I have UIImageView inside UIView and I want to handle event, when user tap on UIView background, but not on UIImageView. How can I achieve it? I read about UITapGestureRecognizer, but it confuse me a little.

P.S. If u can plz answer in swift.

Panich Maxim
  • 1,105
  • 1
  • 15
  • 34

2 Answers2

1

If you want to disable UITapGestureRecognizer on the child view of your main view then you have to enable User Interaction of your UIImageView like this

imgTest.userInteractionEnabled = true;

then you have to set the Delegate of your UITapGestureRecognizer to detect the UITouch of the view, set the delegate like this

let touch  = (UITapGestureRecognizer(target: self, action: "tapDetected:"))
touch.delegate = self
self.view.addGestureRecognizer(touch)

Then you have to implement the Delegate method of UITapGestureRecognizer in which you will detect the view which is currently touched like this

func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldReceiveTouch touch: UITouch) -> Bool {
    if touch.valueForKey("view")!.isKindOfClass(UIImageView) {
        return false
    } else {
        return true
    }
}

In the above code i have disable the tap gesture on UIImageView

Now, this method will work only for your self.view not for UIImageView

func tapDetected(sender: UITapGestureRecognizer) {
        self.dismissViewControllerAnimated(false, completion: nil)
}
Rajat
  • 10,977
  • 3
  • 38
  • 55
0

Add this line for your imageView because UIImageView default user interaction is disable. If you will enable UIImageView userinteraction then it will not work for your UIView and outside of UIImageView it will work

yourImage.userInteractionEnabled = YES;

Try this your tap clicked will work

Jogendra.Com
  • 6,394
  • 2
  • 28
  • 35
  • I tried, it didn't help. override func viewDidLoad() { self.view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: "tapDetected:")) imgView.userInteractionEnabled = true } + func tapDetected(sender: UITapGestureRecognizer) { self.dismissViewControllerAnimated(false, completion: nil) } – Panich Maxim Sep 09 '15 at 14:14
  • Did you define number of taps and touched required and also enabled User Inter. on the view you want to be touchable ? But basically you should be able to achieve it by (Obj-C - Sorry no swift, but should give you the main idea) `UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap)]; singleTap.numberOfTapsRequired = 2; singleTap.numberOfTouchesRequired = 1; [_view addGestureRecognizer:singleTap];` – Radim Halfar Sep 09 '15 at 15:25