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 =
USING A SINGLE TAG FOR ROWS AND SECTIONS
There is a simple way to use tags for transmitting the row/item AND the section of a TableView/CollectionView at the same time.
Encode the IndexPath for your UIView.tag in cellForRowAtIndexPath :
buttonForCell.tag = convertIndexPathToTag(with: indexPath)
Decode the IndexPath from your sender in your target selector:
@IBAction func touchUpInsideButton(sender: UIButton, forEvent event: UIEvent) {
var indexPathForButton = convertTagToIndexPath(from: sender)
}
Encoder and Decoder:
func convertIndexPathToTag(indexPath: IndexPath) -> Int {
var tag: Int = indexPath.row + (1_000_000 * indexPath.section)
return tag
}
func convertTagToIndexPath(from sender: UIButton) -> IndexPath {
var section: Int = Int((Float(sender.tag) / 1_000_000).rounded(.down))
var row: Int = sender.tag - (1_000_000 * section)
return IndexPath(row: row, section: section)
}
Provided that you don’t need more than 4294967296 rows/items on a 32bit device ;-) e.g.
—-
WARNING: Keep in mind that when deleting or inserting rows/items in your TableView/CollectionView you have to reload all rows/items after your insertion/deletion point in order to keep the tag numbers of your buttons in sync with your model.
—-