johnniexo88 johnniexo88 - 3 months ago 29
iOS Question

How to get label on button click in tableview cell for prepareForSegue

I have a tableview. i need to get the label "usernameLabel" from that cell and assign a variable to them. I need to pass that variable to prepareForSegue. The problem is the label is the wrong label from the wrong cell.

here is what i have:

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
}
}


simplified question: i need to pass the label.text to another view controller via segue. but currently, it is getting the label from the wrong cell.

Answer

cellForRowAtIndexPath method will be multiple times so assigning value in that method will not work, also why are you using tapGesture on button instead of adding action to button, try to change your cellForRowAtIndex like this.

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
} 

Now add this buttonAction function inside your ViewController

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)
}