0

I'm building a simple TableViewController, with a Custom TableViewCell.

In this TableViewCell I have

1) ImageView 2) Label 3) Switch Button

Now for example I have when I try to start my application 5 row. I want to start a method if the user click on switch button of one of the rows items.

So I have build this method:

@IBAction func attivaLuci(sender: UISwitch) {
        if sender.on {
            //ATTIVO LA LUCE CORRISPONDENTE
        }else{
            //DISATTIVO LA LUCE CORRISPONDENTE
        }
    }

now how can I get the rowIndex of the cell?

bircastri
  • 2,169
  • 13
  • 50
  • 119
  • Possible duplicate of [iOS Swift Button action in table view cell](http://stackoverflow.com/questions/28894765/ios-swift-button-action-in-table-view-cell) – Sahil Apr 14 '17 at 10:38

3 Answers3

1

Use this

 let row = sender.convert(sender.frame.origin, to: self.tableview)
 let indexPath = self.tableview.indexPathForRow(at: row)

or simply

switchbutton.tag = indexPath.row
@IBAction func attivaLuci(sender: UISwitch) 
{
  let rowindex = sender.tag      
}
Lalit kumar
  • 1,797
  • 1
  • 8
  • 14
0
  • you can use tag property. Any subclass of UIView can use this property to distinguish an object from another.

like you can set buttonA.tag = 101 and buttonB.tag = 102 when they are created. when you want distinguish them just write : if(button.tag == 101).

  • or you can distinguish them by cell, using indexPath.row
Roy Wang
  • 48
  • 7
0

In Swift an easy and smart way is a callback closure.

In the custom cell declare a variable callback

var callback : ((Bool) -> ())?

and call the method in the IBAction

@IBAction func attivaLuci(sender: UISwitch) {
   callback?(sender.isOn)
}

In the table view controller in cellForRowAt set the callback

  func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
      let cell = tableView.dequeueReusableCell...
   ...
      cell.callback = { isOn in
        // execute code, the index path is captured.
        // isOn is the current state of the switch
      }
   ...
  }

When the IBAction in the custom cell is called the closure of the callback is executed.

vadian
  • 274,689
  • 30
  • 353
  • 361