从UIViewController类

时间:2017-06-23 10:53:29

标签: ios swift3 xcode8

我有一个带UITableView的视图控制器。表视图有2个单元格。其中一个单元有一个UISwitch。

在单元格类中,我声明了UISwitch

    cellSwitch.addTarget(self, action: #selector(switchChanged), for: UIControlEvents.valueChanged)

和一个功能

func switchChanged(mySwitch: UISwitch) {
    let value = mySwitch.isOn
    // Do something
    print("mySwitch.isOn: \(value)")

}

我怎么知道我改变了哪个UISwitch实例。我在运行时有几个形成

2 个答案:

答案 0 :(得分:1)

创建单元格时,将数据源索引添加为UISwitch标记。

UISwitch值更改时,获取控件的标记值。并使用通过控制标记获得的索引值从数据源数组中获取数据。

您应该在UIViewController中实现UISwitch值更改方法。否则你必须将数据源数组传递给每个单元格,这是不好的。

细胞创建

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = // Your code here ....

        // Implement UISwitch action method in the UIViewController only.
        cell.cellSwitch.addTarget(self, action: #selector(switchChanged), for: UIControlEvents.valueChanged)

        cell.cellSwitch.tag = indexPath.row
        return cell
}

切换值已更改:

func switchChanged(mySwitch: UISwitch) {

    let value = mySwitch.isOn
    // Do something
    print("mySwitch.isOn: \(value)")

    // tag will give you the index of the data model.
    let index = mySwitch.tag

    //dataSourceArray is your tableview data source array. You can't get this array from cell. so better you should implement UISwitch value change method in the UIViewController. 
    let model = dataSourceArray[index];

    // Now you got the model to update based on switch value change.

}

答案 1 :(得分:1)

在自定义单元格类中,只需从storyBoard创建UISwitch按钮的插座和操作,如下所示

import UIKit
protocol CellDelegate: class {
    func didTapCell(index: IndexPath)
}
class CustomeTableViewCell: UITableViewCell {
 @IBOutlet weak var switchButton: UIButton!
 var delegateCell:CellDelegate?
 var indexPath:IndexPath?

 @IBAction func yourSwitchButton(mySwitch: UISwitch) {
        delegateCell?.didTapCell(index: indexPath!)
    }
}

在您的ViewController类中

class ViewController: UIViewController,CellDelegate {
   func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
     let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: 
     indexPath) as! CustomCell
    cell.delegateCell = self
    cell.indexPath = indexPath
 }
 func didTapCell(index: IndexPath){
    print("YOU SELECTED SWITCH   \(index.row)")
  }
}