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

后端 未结 10 1438
萌比男神i
萌比男神i 2021-02-04 00:43

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

10条回答
  •  悲&欢浪女
    2021-02-04 01:26

    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)")
    }
    

提交回复
热议问题