点击tableview中的button – 错误的单元格
嗨,我想在单元格中传递一个variables,这是我单击单元格中的button时的标签。 但问题是每当我把代码放在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我传递索引作为一个单元属性