Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to attach UITapGestureRecognizer to UILabel subclass

I'm trying to attach gesture recognizer to my own class which is subclass of UILabel, but it does not work. Can you help me to understand what's wrong in the code

  @interface Card : UILabel  {  }  - (void) addBackSideWord;  @end  #import "Card.h"  @implementation Card - (id)initWithFrame:(CGRect)frame {      if ((self = [super initWithFrame:frame])) {          UITapGestureRecognizer *tapRecognizer = [[UITapGestureRecognizer alloc]                          initWithTarget:self action:@selector(addBackSideWord)];         [tapRecognizer setNumberOfTouchesRequired:2];         [tapRecognizer setDelegate:self];         [self addGestureRecognizer:tapRecognizer];     }      return self; }  - (void) addBackSideWord {       //do something } @end  
like image 396
Michael Avatar asked Jun 15 '11 09:06

Michael


People also ask

How to add tap gesture recognizer to UIView?

Adding a Tap Gesture Recognizer to an Image View in Interface Builder. Open Main. storyboard and drag a tap gesture recognizer from the Object Library and drop it onto the image view we added earlier. The tap gesture recognizer appears in the Document Outline on the left.

How to add tap gesture on UIImageView in swift?

Open the Library, look for "Tap Gesture Recognizer" object. Drag the object to your storyboard, and set the delegate to the image you want to trigger actions. Then go to the view controller, drag the same object to set the IBAction.


1 Answers

Your code should work fine, the only thing you may need to fix is that user interaction is disabled for UILabel by default, so gesture recogniser does not receive any touch events. Try manually enable it by adding this line to your code (e.g. in init method):

self.userInteractionEnabled = YES; 
like image 101
Vladimir Avatar answered Oct 08 '22 22:10

Vladimir