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 assoc
For Swift 3
let tapGesture : UITapGestureRecognizer = UITapGestureRecognizer.init(target: self, action:
#selector(lblClick(tapGesture:)))
tapGesture.delegate = self
tapGesture.numberOfTapsRequired = 1
cell.lbl.isUserInteractionEnabled = true
cell.lbl.tag = indexPath.row
cell.lbl.addGestureRecognizer(tapGesture)
And then
func lblClick(tapGesture:UITapGestureRecognizer){
print("Lable tag is:\(tapGesture.view!.tag)")
}
Update for 2019 with Swift 5, based upon Hardik Thakkar's solution. To detect taps on a UIlabel in a cell, find the cellForRowAt method in your view controller below.
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {}
Place the following code in to the method above before returning the cell:
let tapGesture : UITapGestureRecognizer = UITapGestureRecognizer.init(target: self, action: #selector(labelTap(tapGesture:)))
tapGesture.delegate = self
tapGesture.numberOfTapsRequired = 1
cell.yourLabel.isUserInteractionEnabled = true
cell.yourLabel.tag = indexPath.row
cell.yourLabel.addGestureRecognizer(tapGesture)
return cell
Add a method to your view controller to handle the taps:
@objc func labelTap(tapGesture:UITapGestureRecognizer){
print("Label tag is:\(tapGesture.view!.tag)")
}
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];
The way Dinesh suggested will work without the for loop using the property variable.
UITapGestureRecognizer *tap=[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction)];
[tap setNumberOfTapsRequired:1];
[self.myUILabel addGestureRecognizer:tap];
You can add next in your cell's -awakeFromNib method
UITapGestureRecognizer* gesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGestureRecognizerAction:)];
[self.yourLabel setUserInteractionEnabled:YES];
[self.yourLabel addGestureRecognizer:gesture];