Ios 如何通过TableCellView“自定义”的开关按钮获取行索引

Ios 如何通过TableCellView“自定义”的开关按钮获取行索引,ios,swift,xcode,Ios,Swift,Xcode,我正在构建一个简单的TableViewController,带有一个自定义的TableViewCell 在这个TableViewCell里我有 1图像视图 2标签 3开关按钮 例如,当我尝试启动我的应用程序5行时。 如果用户单击其中一行项目的开关按钮,我想启动一个方法 所以我建立了这个方法: @IBAction func attivaLuci(sender: UISwitch) { if sender.on { //ATTIVO LA LUCE CORRI

我正在构建一个简单的TableViewController,带有一个自定义的TableViewCell

在这个TableViewCell里我有

1图像视图 2标签 3开关按钮

例如,当我尝试启动我的应用程序5行时。 如果用户单击其中一行项目的开关按钮,我想启动一个方法

所以我建立了这个方法:

@IBAction func attivaLuci(sender: UISwitch) {
        if sender.on {
            //ATTIVO LA LUCE CORRISPONDENTE
        }else{
            //DISATTIVO LA LUCE CORRISPONDENTE
        }
    }
现在如何获取单元格的行索引?

使用此

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

switchbutton.tag = indexPath.row
@IBAction func attivaLuci(sender: UISwitch) 
{
  let rowindex = sender.tag      
}
您可以使用标记属性。UIView的任何子类都可以使用此属性来区分对象。 就像创建buttonA.tag=101和buttonB.tag=102一样。当您想要区分它们时,只需写:ifbutton.tag==101

或者可以使用indexPath.row按单元格区分它们
在Swift中,一种简单而智能的方法是回调闭包

在自定义单元格中声明一个变量回调

  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
      }
   ...
  }
并在IBAction中调用该方法

在cellForRowAt中的表视图控制器中设置回调

  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
      }
   ...
  }
调用自定义单元格中的iAction时,将执行回调的闭包

可能重复的
  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
      }
   ...
  }