ios - 从单元格中获取标签 - swift

标签 ios swift uitableview uicollectionviewcell

这是我的代码:

var username: String!

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

    username = usernameLabel.text
    cell.button.userInteractionEnabled = true
    let tapButton = UITapGestureRecognizer(target: self, action: #selector(ViewController.tapLabel(_:)))
    cell.button.addGestureRecognizer(tapButton)

    return cell as MainCell
}

func tapButton(sender:UITapGestureRecognizer) {
    print(username) //this prints the wrong cell... why?
}

我希望能够打印变量用户名,但是当我按下按钮时它为单元格打印了错误的用户名。为什么会这样,我该如何解决?

最佳答案

在cellForRowAtIndex中添加标签

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

     cell.button.userInteractionEnabled = true
    cell.button.setTitle( usernameLabel.text, forState: .Normal)
     cell.button.tag = indexPath.row
     cell.button.addTarget(self, action: #selector(ViewController.tapButton(_:)), forControlEvents: .TouchUpInside)

    return cell as MainCell
}

获取 Action 为

func tapButton(sender: UIButton!) 
{
   username =  sender.titleLabel.text
    print(username)  
}

关于ios - 从单元格中获取标签 - swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38929376/

相关文章:

swift - 有没有办法让 Swift 脚本使用多个文件

ios - 如何使用自动调整高度的 SnapKit 以编程方式创建 UITableViewCell?

objective-c - 显示 UITableViewCell,然后可以展开以显示更多数据

ios - 设置为对象时JSON结果为空,但可以打印出结果

ios - 如何使用 Collection View 创建 2 x 2 网格布局?

ios - 函数在闭包完成之前返回 Firebase

ios - 分段控制,改变色调不透明度,但不改变边框

ios - NSFetchedResultsController 添加新记录时如何防止 UITableView 向上滚动?

android - 使用 C++ 为 Android 和 iOS 制作 OpenGLES 2.0 库

ios - 停止更新 map 查看位置