There are certain possible solution to this question:
Solution 1:
- Create a Subclass of UIButton:
class CustomTaggedButton: UIButton {
var section: Int = 0
var row: Int = 0
}
- Assign CustomTaggedButton to your button.
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CellIdentifier", for: indexPath) as! CustomTableViewCell
cell.button.section = indexPath.section
cell.button.row = indexPath.row
button.setTitle("Tap me", for: .normal)
button.addTarget(self, action: #selector(buttonTapped(_:)), for: .touchUpInside)
return cell
}
- On button click
func buttonTapped(_ sender: CustomTaggedButton) {
let section = sender.section
let row = sender.row
print("Button tapped - Section: \(section), Row: \(row)")
// Use section and row as needed
}
Solution 2:
https://mcmap.net/q/1321538/-send-row-and-section-through-tag-in-button-swift logical or meaningful solution for this specific answer.
use combination of bit shifting and bitwise operations to pack the section and row information into a single tag value.
- When assigning tags:
let tag = (indexPath.section << 16) | indexPath.row
cell.button.tag = tag
- When extracting section and row:
func buttonTapped(_ sender: UIButton) {
let tag = sender.tag
let section = (tag >> 16) & 0xFFFF
let row = tag & 0xFFFF
print("Button tapped - Section: \(section), Row: \(row)")
// Use section and row as needed
}
Sample tag value from section & row:
Tag for Section 0, Row 0: tag = (0 << 16) | 0 = 0
Tag for Section 1, Row 2: tag = (1 << 16) | 2 = 65538
Tag for Section 2, Row 3: tag = (2 << 16) | 3 = 131075