How can I add a UITapGestureRecognizer to a UILabel inside a table view cell?
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];
}
}
Doing this works without problems:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
...
// create you cell
UILabel *lbl = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 50)];
[lbl setText:@"example"];
[lbl setUserInteractionEnabled:YES];
[cell.contentView addSubview:lbl];
UITapGestureRecognizer *tap=[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
tap.tag = [NSIndexPath row];
[tap setNumberOfTapsRequired:1];
[lbl addGestureRecognizer:tap];
...
}
- (void)tapAction:(id)sender {
switch(((UITapGestureRecognizer *)sender).view.tag) {
case 0:
// code
break;
case 1:
// code
break;
....
}
}
even in the case in which creates the UILabel with IB
UITapGestureRecognizer *recognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction)];
[recognizer setNumberOfTapsRequired:1];
lblName.userInteractionEnabled = YES;
[lblName addGestureRecognizer:recognizer];