Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I add a UITapGestureRecognizer to a UILabel inside a table view cell?

Tags:

I am using a NIB file to layout a custom table view cell. This cell has a label with outlet called lblName. Adding a UITapGestureRecognizer to this label never fires the associated event. I have userInteractionEnabled = YES.

I'm guessing that the problem is that the UILabel is in a TableView and that the table/cell view is intercepting the taps. Can I do something about this?

All I want to do is perform some custom action when a UILabel is pressed! All of the solutions for doing this that I've seen are ridiculous. It should be easy using the standard tool set. But evidently not.

Here's the code I'm using:

- (void)tapAction {     NSLog(@"Tap action"); }  - (void)viewDidLoad {     [super viewDidLoad];     // Do any additional setup after loading the view from its nib      UITapGestureRecognizer *recognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction)];      [recognizer setNumberOfTapsRequired:1];     //lblName.userInteractionEnabled = true;  (setting this in Interface Builder)     [lblName addGestureRecognizer:recognizer]; } 
like image 627
Bryan Avatar asked Apr 09 '12 19:04

Bryan


People also ask

How do I make a UILabel clickable?

To make UILabel clickable you will need to enable user interaction for it. To enable user interaction for UILabel simply set the isUserInteractionEnabled property to true.


2 Answers

EASY WAY:

You may also use a invisible button on the top of that label. So it will reduce your work of adding tapGesture for that label.

ALTERNATIVE WAY:

You should not create an IBOutlet for that UILabel. When you do that,you will add a outlet in custom class implementation file. You cannot access in other file. So set a tag for that label in custom class IB and write a code in cellForRowAtIndexPath: method.

UPDATED:

In cellForRowAtIndexPath: method,

for(UIView *view in cell.contentViews.subviews) {     if(view.tag == 1) {         UITapGestureRecognizer *tap=[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction)];         [tap setNumberOfTapsRequired:1];         [view addGestureRecognizer:tap];     } } 
like image 80
Dinesh Raja Avatar answered Sep 22 '22 06:09

Dinesh Raja


UITapGestureRecognizer *recognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction)];  [recognizer setNumberOfTapsRequired:1]; lblName.userInteractionEnabled = YES;   [lblName addGestureRecognizer:recognizer]; 
like image 45
sarit bahuguna Avatar answered Sep 20 '22 06:09

sarit bahuguna