2016-08-10 56 views
0

我有一个标签,我想使用addGestureRecognizer。我把它放在cellForRowAtIndexPath,但是当我做print(label.text)时,它从另一个单元打印标签。但是当我将它放入didSelectRowAtIndexPath时,它会打印出该单元的正确标签。点击表格视图中的标签?

解决此问题的最佳方法是什么?

下面是代码:

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) 
    } 
+2

您可以显示的tableview执行'cellForRowAtIndexPath'代码和动作代码 –

+0

使用自定义的UITableViewCell类。 –

+0

@ Anbu.Karthik刚刚编辑过文章 – johnniexo88

回答

1

我想你忘记设置tap.tag = indexPath.row用于识别找到你标签,其细胞,例如

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 tapLabel(sender:UITapGestureRecognizer) { 

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

请问您可以根据我上面编辑的问题更改答案吗? – johnniexo88

+0

@ johnniexo88 - ya sure –

+0

@ johnniexo88 - 查看更新后的答案 –

0

有与您当前密码的几个问题:(1)您将variableToPass设置为cellForRowAtIndexPath:,因此假设label1.text是属于该单元格的标签,随着表格加载,variableToPass将始终包含上次加载的单元格的标签文本。 (2)cellForRowAtIndexPath:可以为每个单元格调用多次(例如,在您滚动时),以便您可以将多个手势识别器添加到单个单元格。

为了解决问题#1,请完全删除variableToPass变量,而是直接访问手势的标签视图。为了解决问题#2,我建议将手势识别器添加到您的自定义MainCell表视图单元格中,但如果您不想这样做,至少只添加一个手势识别器(如果尚未存在)。

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 

    let cell = tableView.dequeueReusableCellWithIdentifier("MainCell") as! MainCell 

    if cell.label1.gestureRecognizers?.count == 0 { 
     cell.label1.userInteractionEnabled = true 

     let tapLabel = UITapGestureRecognizer(target: self, action: #selector(ViewController.tapCommentPost(_:))) // I assume "tapLabel" was a typo in your original post 
     cell.label1.addGestureRecognizer(tapLabel) 
    } 

    return cell 
} 

func tapCommentPost(sender:UITapGestureRecognizer) { 
    print((sender.view as! UILabel).text) // <-- Most important change! 
} 
相关问题