我想要使用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)
}
答案 0 :(得分:2)
我认为您忘记设置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)
}
答案 1 :(得分:1)
您当前的代码存在以下问题:(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!
}