点击表格视图中的按钮 - 错误的单元格 [英] Tap button in tableview - wrong cell
问题描述
我试图在单元格中传递一个变量,这是当我单击单元格中的按钮时的标签.但问题是每当我将代码放入 cellForRowAtIndexPath 时,它每次都会从错误的单元格中获取标签.为什么以及如何解决这个问题?
Hi I am trying to pass a variable in the cell which is the label when i click on a button in the cell. but the problem is every when I put the code in cellForRowAtIndexPath, it gets the label from the wrong cell every time. why and how to fix this?
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
:
The way your code is set up, variableToPass
is always the text in the last cell acquired from dequeueReusableCellWithIdentifier
. Instead, set variableToPass
in your tapButton
method, because then you know what cell was selected and you can correctly set variableToPass
:
func tapButton(sender:UITapGestureRecognizer) {
let label = sender.view as! UILabel
self.variableToPass = label.text
performSegueWithIdentifier("SegueIdentifierName", sender: self)
}
这篇关于点击表格视图中的按钮 - 错误的单元格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!