[英]How to get label on button click in tableview cell for prepareForSegue
我有一张桌子。 我需要从该单元格获取标签“ usernameLabel”,并为其分配一个变量。 我需要将该变量传递给prepareForSegue。 问题是标签是来自错误单元格的错误标签。
这是我所拥有的:
var username: String!
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell : MainCell! = tableView.dequeueReusableCellWithIdentifier("MainCell") as! MainCell
username = usernameLabel.text
cell.button.userInteractionEnabled = true
let tapButton = UITapGestureRecognizer(target: self, action: #selector(ViewController.tapLabel(_:)))
cell.button.addGestureRecognizer(tapButton)
return cell as MainCell
}
func tapButton(sender:UITapGestureRecognizer) {
performSegueWithIdentifier("ViewToView2Segue", sender: self)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "ViewToView2Segue" {
let userProfileViewController = segue.destinationViewController as! SecondViewController
secondViewController.usernamePassed = usernamePassed
}
}
简化的问题:我需要通过segue将label.text传递给另一个视图控制器。 但目前,它是从错误的单元格获取标签。
cellForRowAtIndexPath
方法将多次出现,因此无法在该方法中分配值,这也是为什么要在按钮上使用tapGesture
而不是向按钮添加动作,因此尝试更改cellForRowAtIndex
这样。
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell : MainCell! = tableView.dequeueReusableCellWithIdentifier("MainCell") as! MainCell
cell.button.setTitle( usernameLabel.text, forState: .Normal)
cell.button.addTarget(self, action: #selector(self.buttonAction(_:)), forControlEvents: .TouchUpInside)
return cell
}
现在,在您的ViewController
添加此buttonAction
函数
func buttonAction(sender: UIButton) {
let center = sender.center
let point = sender.superview!.convertPoint(center, toView:self.tableView)
let indexPath = self.tableView.indexPathForRowAtPoint(point)
let cell = self.tableView.cellForRowAtIndexPath(indexPath) as! MainCell //Add superview on the basis of your button hierarchy in the cell
username = cell.usernameLabel.text
print(username)
performSegueWithIdentifier("ViewToView2Segue", sender: self)
}
您不应将状态数据保存在单元格中。 您应该在模型中拥有所需的信息(可能是数组)。 当用户点击一个单元格时,您应该使用所选单元格的indexPath从模型而不是从该单元格上的标签中获取信息。
(在MVC设计模式中查找背景。表视图单元是视图对象,不应存储数据。这是模型的工作。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.