7
votes

I've created a custom subclass of UIView because I needed to override drawRect method. I try to add a UITapGestureRecognizer to it, but this doesn't work for me. Here, the code of my ViewController:

MyCustomView *customView = [[MyCustomView alloc] initWithFrame:CGRectFrame(0, 30, 30, 30)];
[customView setUserInteractionEnabled:YES];

UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(doSomething)];
[customView addGestureRecognizer:tapGestureRecognizer];

I don't understand why when I touch my UIView subclass object, the gesture recognizer doesn't fire up.

Thanks a lot in advance !

FIXED IT OUT !

My view was on a UIImageView, and that UIImageView hadn't the userInteractionEnabled set to YES.

4
is your bounds/frame correct? - CarlJ
Apparently yes, my sublass is in fact a circle drawn with CoreGraphics. the frame is: 10, 30, 30, 30. - Vinestro
For information (it may help), the code I show you is in the tableView:cellForRowAtIndexPath method. One idea ? - Vinestro
in this case it would be better, if you declare your customView as an UIControl and not as an UIView and remove the UITapGestureRecognizer and add a target (like adding a target to an UIButton) to your CustomView - CarlJ
I tried with UIControl, it doesn't work too. - Vinestro

4 Answers

13
votes

FIXED IT OUT !

My view was on a UIImageView, and that UIImageView hadn't the userInteractionEnabled set to YES.

0
votes

Make sure you are displaying it somewhere (addSubview).

0
votes

Also make sure that userInteractionEnabled is set to true. If that's true, post the code that creates and hooks up the gesture recognizer.

0
votes

Set the UserInteractionEnable check to true on the subview that you are adding and in the selector method, do pass the object along with it i.e.

UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(doSomething:)];

and make the selector method as

-(void) doSomething:(UITapGestureRecognizer *)gesture;

Let me know if you are still having an issue. Thanks!