嗨我试图在单元格中传递一个变量,当单击单元格中的按钮时,该变量是标签。但问题是每次将代码放入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
}
}
您应该分离出你的代码和子类的UITableViewCell,然后在子类中创建点击手势识别器。此外,您需要将手势识别器的代表设置为CELL。 – Loxx
您可以使用'didSelectRowAtIndexPath'委托方法。 –
@DharmeshKheni你可以,我一直这样做,但从来没有像这样,总是在UITableViewCell的子类中,从来没有在控制器 – Loxx