繁体   English   中英

点击表格视图中的按钮-错误的单元格

[英]Tap button in tableview - wrong cell

嗨,我试图在单元格中传递一个变量,当我单击单元格中的按钮时,该变量就是标签。 但是问题是每当我将代码放在cellForRowAtIndexPath中时,它每次都会从错误的单元格获取标签。 为什么以及如何解决这个问题?

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 tapButton = UITapGestureRecognizer(target: self, action: #selector(ViewController.tapLabel(_:)))
    cell.label1.addGestureRecognizer(tapButton)

    return cell as MainCell
}

func tapButton(sender:UITapGestureRecognizer) {
    performSegueWithIdentifier("SegueIdentifierName", sender: self)
}

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if segue.identifier == "SegueIdentifierName" {
        let viewController = segue.destinationViewController as! ViewController
        viewController.getVariablePassed = variableToPass
    }
}

设置代码的方式, variableToPass始终是从dequeueReusableCellWithIdentifier获取的最后一个单元格中的文本。 相反,请在tapButton方法中设置variableToPass ,因为这样您就知道选择了哪个单元格,并且可以正确设置variableToPass

func tapButton(sender:UITapGestureRecognizer) {
    let label = sender.view as! UILabel
    self.variableToPass = label.text
    performSegueWithIdentifier("SegueIdentifierName", sender: self)
}

我的方法是使用单元格委托并将我的viewController注册为该单元格的委托,稍后当用户点击UIButton时,我将调用类似

- (void)buttonWasPressedWithIndexPath:(NSIndexpath*)indexPath

在cellForRowAtIndexPath中,我将indexPath作为单元格属性传递

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM