swift - 在 Swift 的 UITableView 单元格中添加开关

标签 swift uitableview swift3 cell uiswitch

如何在 Swift 中以编程方式将 UISwitch 嵌入到 tableView 单元格中? 我就是这样做的

let shareLocationSwitch = UISwitch()
cell.accessoryView = shareLocationSwitch

最佳答案

您可以通过以下方式将 UISwitch 嵌入到 UITableView 单元格中。

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {        
                var cell = tableView.dequeueReusableCell(withIdentifier: "yourcellIdentifire", for: indexPath) as! YourCellClass

                       //here is programatically switch make to the table view 
                        let switchView = UISwitch(frame: .zero)
                        switchView.setOn(false, animated: true)
                        switchView.tag = indexPath.row // for detect which row switch Changed
                        switchView.addTarget(self, action: #selector(self.switchChanged(_:)), for: .valueChanged)
                        cell.accessoryView = switchView

               return cell
      }

这里是switch调用beck方法

func switchChanged(_ sender : UISwitch!){

      print("table row switch Changed \(sender.tag)")
      print("The switch is \(sender.isOn ? "ON" : "OFF")")
}

@LeoDabus Great! explanation.

注意:如果您的 tableview 可能有多个 section,那么您应该创建一个 CustomCell 子类 UITableViewCell 并配置您的 accessoryView inside UITableViewCell awakeFromNib 方法而不是 TableView cellForRowAt 方法。将可重复使用的 cell 出队时将其转换为您的 CustomCell Here is sample from @LeoDabus

关于swift - 在 Swift 的 UITableView 单元格中添加开关,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47038673/

相关文章:

ios - Swift Action 键不起作用

ios - Swift:异步回调

ios - 禁用不同 ViewController 中的按钮 - Swift 3

ios - Swift 3 - UserDefaults 无故自动清除

swift - 为什么 'self' 在类之外使用?

ios - 我应该如何修复 Nimble 文件中的错误?

ios - 如何定位 Google 地点自动完成功能?

json - 编写 JSON 序列化函数

arrays - 使用数组中的值将 Section 添加到 tableView

ios - 创建需要 NSCoder 的子类实例