Is it possible to attach UITapGestureRecognizer to UILabel subclass

Michael picture Michael · Jun 15, 2011 · Viewed 9.4k times · Source

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

Answer

Vladimir picture Vladimir · Jun 15, 2011

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;