Ios 从cell-swift获取标签

Ios 从cell-swift获取标签,ios,swift,uitableview,uicollectionviewcell,Ios,Swift,Uitableview,Uicollectionviewcell,这是我的密码: var username: String! func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell : MainCell! = tableView.dequeueReusableCellWithIdentifier("MainCell") as! MainCell username

这是我的密码:

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?
}

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

它将打印存储在
username
中的
最新值
,因为单元格的每个
indexath
,它将更新
用户名中的值
&最后将为您提供
最新更新值
,无论您点击哪个单元格

在cellforrowatinex中添加标记

 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
}
采取行动

func tapButton(sender: UIButton!) 
{
   username =  sender.titleLabel.text
    print(username)  
}
1) 在cellForRowAtIndexPath:方法中,将按钮标记指定为索引:

cell.yourbutton.tag = indexPath.row;
2) 为按钮添加目标和操作,如下所示:

cell.yourbutton.addTarget(self, action: #selector(self.yourButtonClicked), forControlEvents: .TouchUpInside)
3) 在ViewControler中根据索引对操作进行编码,如下所示:

func yourButtonClicked(sender: UIButton) {
    if sender.tag == 0 {
        // Your code here

    }
}

参考SO:

您应该在MainCell中实现操作按钮。您可以使用用户名,这是最佳做法;)


为什么希望打印正确的值
cellforrowatinexpath
被多次调用,因此
username
将仅具有最后引用的单元格的值。但是您尝试为每个单元格打印该值。为什么使用getsure for按钮,无需直接获取索引这也是错误的username=usernamelab。text@rmaddy哦,我明白了。那么解决方案是什么?那么解决方案是什么?这意味着你的单元格只打印最后一个值,检查更新后的答案你在点击时得到了正确的用户名根据单元格的索引路径设置视图的标记是不好的做法。只有当有一个节且行是静态的(没有添加、删除或重新排序)时,这才有效。titleLabel.text是什么?它是UIButton属性,您可以使用按钮单击@rmaddy-我同意,如果sender.tag==0给了我这个错误:[UITapGestureRecognizer tag]:发送到实例0x7f的无法识别的选择器……**由于未捕获的异常“NSInvalidArgumentException”而终止应用程序,原因:'-[UITapgestureRecognitizer标记]:未识别的选择器已发送到实例0x7f…。。。
class MainCell: UITableViewCell {
   @IBOutlet weak var usernameLabel: UITextView!

   func tabButton(sender: AnyObject) {
       print(usernameLabel.text)
   } 
}