我有一个标签,我想使用 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)
}
最佳答案
我想你忘记设置 tap.tag = indexPath.row
来识别你为 Find 选择的单元格,例如
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)
}
关于ios - 在表格 View 中点击标签?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38864022/