I have a tableview with buttons and I want to use the indexpath.row when one of them is tapped. This is what I currently have, but it always is 0
var point =
In my case i have multiple sections and both the section and row index is vital, so in such a case i just created a property on UIButton which i set the cell indexPath like so:
fileprivate struct AssociatedKeys {
static var index = 0
}
extension UIButton {
var indexPath: IndexPath? {
get {
return objc_getAssociatedObject(self, &AssociatedKeys.index) as? IndexPath
}
set {
objc_setAssociatedObject(self, &AssociatedKeys.index, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
}
Then set the property in cellForRowAt like this :
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell") as! Cell
cell.button.indexPath = indexPath
}
Then in the handleTapAction you can get the indexPath like this :
@objc func handleTapAction(_ sender: UIButton) {
self.selectedIndex = sender.indexPath
}