0

I have a simple table view, with a custom cell build in it, the custom cell has two buttons ( later they will be used as Down Vote and UpVote buttons ), is there a way for to pass the indexPath.row value to the button, in order to me to identify which cell button was clicked?

TablewViewController.swift

 override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as CustomTableViewCell

        cell.piadaTitulo.text = "Lorem Ipsum"
        cell.piadaDescription.text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean commodo volutpat lectus, vitae semper tortor finibus at. Cras erat ligula, egestas sed tincidunt eget, condimentum maximus lectus. Aenean varius semper tellus, id congue lacus pretium a"


        return cell
    }

CustomTableViewCell.Swift

@IBOutlet weak var piadaTitulo: UILabel!
@IBOutlet weak var piadaDescription: UILabel!

@IBAction func piadaUpVote(sender: AnyObject) {
    println("UPVOTE clicked")
}

@IBAction func piadaDownVote(sender: AnyObject) {
    println("DOWNVOTE clicked")
}

Simple Table View

2
  • you could assign the tag property to the row in your cellForRowAtIndexPath function. Then just use sender.tag in the IBActions to know the row. Commented Apr 22, 2015 at 19:11
  • i should add the tag to the cell? like cell.tag = indexPath.row? Commented Apr 22, 2015 at 19:23

2 Answers 2

3

Screw tags. Use this extension for an easy find of the indexPath of the button's cell.

// MARK: - UITableView
extension UITableView {
    func indexPathForView (view : UIView) -> NSIndexPath? {
        let location = view.convertPoint(CGPointZero, toView:self)
        return indexPathForRowAtPoint(location)
    }
}

@IBAction func pressedButton(sender: AnyObject) {
    // For a button press
    let button = sender as! UIButton
    var indexPath = self.tableView.indexPathForView(button)!

    // Do thangs
}
Sign up to request clarification or add additional context in comments.

Comments

0

You also could get the superview of the button which is the cell itself, and you dont need the indexpath

sender.superview

Regards

1 Comment

Not in every case. contentView, subviews?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.