1

How to get the indexPath.row of a particular cell when a button in the cell is tapped here is my code

if let indexPath = self.tableView?.indexPathForSelectedRow {
    print("\(indexPath.row)")

}
Paulw11
  • 108,386
  • 14
  • 159
  • 186
lordxxx
  • 49
  • 1
  • 8
  • If they have tapped the button, it probably won't be the seleced row, since the button was tapped, not the row. You need to get a reference to the cell and use `indexPathForCell` – Paulw11 Aug 14 '16 at 09:49

2 Answers2

3

Get the cell from button(sender) action

 var cell: UITableViewCell = sender.superview.superview as UITableViewCell

Get the indexpath

 tableView.indexPathForCell(cell)
Sofeda
  • 1,361
  • 1
  • 13
  • 23
  • This is a bad approach. It makes too many assumptions about the layout of the table cell. The layout has changed in the past and code like this breaks as a result. Don't use this approach. – rmaddy Feb 03 '17 at 18:13
  • Please describe a little more. i don't get it. May be i am missing something. Let me help :) – Sofeda Feb 05 '17 at 05:09
1

When a button is tapped in your cell, you need to traverse up the chain of that button's superviews to obtain reference to the UITableViewCell. Once there, you can ask the tableView for the indexPath by using the tableView.indexPathForCell(cell: UITableViewCell) function.

Something like this:

var optionalCell: UITableViewCell? = nil
var view: UIView = yourButton

while view.superView != nil {
  view = view.superView
  if view is UITableViewCell {
    optionalCell = view
    break
  }
}

if let cell = optionalCell {
  var indexPath = tableView.indexPathOfCell(cell)
} else {
  return
}

I don't know how your code looks, but that is what it should look like. Of course, you could always hack it I suppose and know exactly how many superViews up the cell (UITableViewCell) is compared to your button, but this'll work regardless of how deep within your cell view hierarchy the button is.

David
  • 7,028
  • 10
  • 48
  • 95
  • It would be preferable to establish a delegation protocol between cell and table ViewController and have the cell pass a reference to itself to the delegate when the button is tapped – Paulw11 Aug 14 '16 at 10:25