【问题标题】:getting uiswitch value in cell from UIViewController class从 UIViewController 类获取单元格中的 uiswitch 值
【发布时间】:2017-06-23 10:53:28
【问题描述】:

我有一个带有 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 的哪个实例。我在运行时有几个成形

【问题讨论】:

  • 你的意思是在单个单元格中你有多个 UISwitch ?

标签: ios swift3 xcode8


【解决方案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.

}

【讨论】:

    【解决方案2】:

    在您的自定义单元格类中,只需从 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)")
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-05-16
      • 2011-04-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多