您好我正在尝试在单元格中传递一个变量,当我单击单元格中的按钮时,该变量是标签。但问题是每当我将代码放在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
}
}
答案 0 :(得分:1)
设置代码的方式,variableToPass
始终是从dequeueReusableCellWithIdentifier
获取的最后一个单元格中的文本。相反,在variableToPass
方法中设置tapButton
,因为您知道选择了哪个单元格,并且可以正确设置variableToPass
:
func tapButton(sender:UITapGestureRecognizer) {
let label = sender.view as! UILabel
self.variableToPass = label.text
performSegueWithIdentifier("SegueIdentifierName", sender: self)
}
答案 1 :(得分:0)
我的方法是使用单元格委托并将我的viewController注册为单元格的委托,稍后当用户点击UIButton时我将调用类似
的方法 - (void)buttonWasPressedWithIndexPath:(NSIndexpath*)indexPath
并在cellForRowAtIndexPath中我将indexPath作为单元格属性传递