Josh D.
Josh D.

Reputation: 161

Perform Segue from Button in TableViewCell

I have a CustomCell class that has a button. I am using a prototype cell (not a .xib). I would like to have the button in a tableviewcell perform a segue and pass a value to a new class. How do I create a unique action for a button in a tableviewcell? Thanks!

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    ...

    selectedAreaCode = areaCodes[indexPath.row]

    // Configure Cell
    cell.areaCodeButton.setTitle(areaCode, forState: UIControlState.Normal)


    cell.areaCodeButton.addTarget(self, action: "segue", forControlEvents: UIControlEvents.TouchUpInside)

    cell.selectionStyle = UITableViewCellSelectionStyle.None


    return cell
}

func segue() {

    self.performSegueWithIdentifier("toDialer", sender: self)
}

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {

    if(segue.identifier == "toDialer") {

        let nextViewController = (segue.destinationViewController as! PhoneDialer)
        nextViewController.passedAreaCode = selectedAreaCode
    }
}

Upvotes: 1

Views: 980

Answers (1)

jimmyy
jimmyy

Reputation: 139

There's a bunch of ways to get the tap action from your custom cell, but I'm assuming that you're trying to retrieve the action from a UIViewController because you're trying to segue.

Because you're dequeueing a cell, you briefly have full access to the cell in the scope of your cellForRowAtIndexPath function. As long as you have the button as a public property of the cell, you can set that button's target to your segue method.

Also, because what you're trying to pass is in the title of the button itself, you can just access the sender from the selector.

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = yourCell()
    cell.button.addTarget(self, action: #selector(tap(:)), forControlEvents: .TouchUpInside)
}

func segue(sender: UIButton) {
    // Perform segue and other stuff
    sender.title // This is the area code
}

Upvotes: 1

Related Questions