Vadim Nikolaev
Vadim Nikolaev

Reputation: 2132

Get row touched UILabel for cell in TableView

Colleagues, I have a problem with getting of row when I pressed on UILabel in cell in UITableView. So, I have

class CellOfFirstTableView: UITableViewCell

where I have

@IBOutlet weak var labelChangeSomething: UILabel!

with that cell I work in

class FirstTableViewController: UITableViewController

so I'd like to get row for pressed UILabel, but I don't know how to do it. My code for cell and action of press:

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "firstCell", for: indexPath) as! CellOfFirstTableView
    let list = sortOfSomething(id: id_something)[indexPath.row]

    //tapRecognizer
    let tap = UITapGestureRecognizer(target: self, action: #selector(FirstTableViewController.tapFunction))
    cell.labelChangeSomething.isUserInteractionEnabled = true
    cell.labelChangeSomething.addGestureRecognizer(tap)

    return cell
}

and function for action:

func tapFunction(sender:UITapGestureRecognizer) {

print("Hello world")

  }

I'd like to get row of pressed UILabel (when I press in UILabel I see "Hello world", but I want see row in what UILabel is located. I can get row of pressed cell, but user may press only UILabel and don't press part's of cell where UILabel not active. Thanks for your ideas!

Upvotes: 0

Views: 98

Answers (2)

Rohit Pradhan
Rohit Pradhan

Reputation: 3875

1)You can make use of tag property of UIView. Just add tag to the labelChangeSomething in cellForRowAtIndexPath method

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "firstCell", for: indexPath) as! CellOfFirstTableView
    let list = sortOfSomething(id: id_something)[indexPath.row]

    //tapRecognizer
    let tap = UITapGestureRecognizer(target: self, action: #selector(FirstTableViewController.tapFunction))
    cell.labelChangeSomething.isUserInteractionEnabled = true
    cell.labelChangeSomething.addGestureRecognizer(tap)
     //here added tag
    cell.labelChangeSomething.tag = indexPath.row

    return cell
}

2) update your selector method like below

func tapFunction(sender:UITapGestureRecognizer) {

if let label = sender.view as? UILabel {
   //print label tag here == indexpath.row
   print("row = \(label.tag)")
  }

}

Upvotes: 2

J. Koush
J. Koush

Reputation: 1068

You don't need UITapGestureRecognizer when you tap on a label in a cell you are clicking on the cell, you need to call

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)

TableViewDelegate and write this code in it.

let cell = tableView.cellForRow(at: IndexPath) as? CellOfFirstTableView

Upvotes: 0

Related Questions