1

I am working with UISwitch in UITableViewCell and I am passing the row like bellow:

.....
cell.swcSelectCourse.tag = indexPath.row
cell.swcSelectCourse.addTarget(self, action: #selector(handleSWCSelectCourse(sender:)), for: .valueChanged)
.....

@objc func handleSWCSelectCourse(sender: UISwitch){
        let row = sender.tag
        let section = ?????
        let selectedIndex = IndexPath(row: row, section: ????)
}

But I need to section now, how can i pass section to @objc func handleSWCSelectCourse ?

jo jo
  • 1,758
  • 3
  • 20
  • 34
  • 2
    Related: https://stackoverflow.com/questions/50891714/unable-to-save-on-off-state-of-a-uitableviewcell/50894345#50894345. The index path is captured in the closure. – vadian Oct 06 '19 at 09:41
  • @ vadian. I need to have row and section for select values of my custom object. – jo jo Oct 06 '19 at 09:43
  • As I said the index path (section and row) is available in the closure. If cells can be inserted, deleted or moved pass also the cell in the closure to get the actual index path. – vadian Oct 06 '19 at 09:45
  • @ vadian. Your response is true for me. Thank's a lot. Insert your answer and then I accept it. – jo jo Oct 06 '19 at 10:30
  • I marked the question as duplicate. – vadian Oct 06 '19 at 10:35

2 Answers2

1

Using the tag is really a hack, but as long as you're going for that, just use some of the tag bytes for the row and the others for the section. For example:

cell.swcSelectCourse.tag = indexPath.row + indexPath.section * 0x1000

/// and then later:
let row = tag % 0x1000
let section = tag / 0x1000

Of course, make sure you leave enough bytes for the expected number of rows and sections. And please, bounds check.

Yonat
  • 4,382
  • 2
  • 28
  • 37
0

In my opinion, you should use delegate like this sample code

protocol SelectCourseCellDelegate: class {
     func didChangeSwitchValue(_ cell: Your Table View Cell, value: Bool)
}