johnniexo88 johnniexo88 - 3 months ago 9
Swift Question

Tap label in table view?

I have a label I want to tap on using

addGestureRecognizer
. I put it in
cellForRowAtIndexPath
but when I do
print(label.text)
, it prints a label from another cell. But when I put it in
didSelectRowAtIndexPath
, it prints out the right label for that cell.

What is the best way to fix this?

Here is the code:

var variableToPass: String!

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let cell : MainCell! = tableView.dequeueReusableCellWithIdentifier("MainCell") as! MainCell

variableToPass = label1.text

cell.label1.userInteractionEnabled = true
let tapLabel = UITapGestureRecognizer(target: self, action: #selector(ViewController.tapLabel(_:)))
cell.label1.addGestureRecognizer(tapLabel)



return cell as MainCell
}

func tapCommentPost(sender:UITapGestureRecognizer) {
print(variableToPass)
}

Answer

I think you forget to set the tap.tag = indexPath.row for identify which cell you tabbed for Find, for example

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
    {
        let cell : MainCell! = tableView.dequeueReusableCellWithIdentifier("MainCell") as! MainCell

        variableToPass = label1.text

        cell.label1.userInteractionEnabled = true
        let tapLabel = UITapGestureRecognizer(target: self, action: #selector(ViewController.tapLabel(_:)))
        cell.label1.tag = indexPath.row
        tapLabel.numberOfTapsRequired = 1
        cell.label1.addGestureRecognizer(tapLabel)



        return cell as MainCell
    }

func tapCommentPost(sender:UITapGestureRecognizer) {

    let searchlbl:UILabel = (sender.view as! UILabel)
    variableToPass =  searchlbl.text!
    print(variableToPass)
    }
Comments