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
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.
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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With