ios - 在表格 View 中点击标签?

标签 ios swift uitableview cell

我有一个标签,我想使用 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/

相关文章:

ios - 查找tableView的哪一行是CollectionView

ios - 如何使用 iOS 7 样式收据查找应用内购买的最新收据

ios - 为什么我的 UIButton 会影响 Swift 中的 UIImageView?

ios - 如何在不弄乱内容的情况下标记 dequeueReusableCell?

swift - ios如何防止键盘出现时导航栏隐藏?

ios - 数据未填充到 TableView

ios - 如何使用 swift 在 Xcode 6 中将 GIF/视频添加到登陆屏幕背景?

ios - 在 UIButton 中禁用字体动画

ios - 从网络服务器(ASIHTTPRequest、PHP、mysql)更新 iOS TableView 单元格中的数据

ios - 滚动时隐藏导航栏而不隐藏状态栏及其背景