How to get rowIndex by switchButton of TableCellView “Custom”

我与影子孤独终老i 提交于 2021-02-11 15:34:31

问题


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?


回答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      
}



回答2:


  • 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



回答3:


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.



来源:https://stackoverflow.com/questions/43409799/how-to-get-rowindex-by-switchbutton-of-tablecellview-custom

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!