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

TAO*_*TAO 10 cell uitableview uiswitch swift swift3

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

let shareLocationSwitch = UISwitch()
cell.accessoryView = shareLocationSwitch
Run Code Online (Sandbox Code Playgroud)

Naz*_*san 21

这是你可以嵌入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
      }
Run Code Online (Sandbox Code Playgroud)

这里是切换调用beck方法

func switchChanged(_ sender : UISwitch!){

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

@LeoDabus Great! explanation.

注意:如果您tableview可能有多个,section那么您应该创建一个CustomCell子类UITableViewCell并配置accessoryView内部UITableViewCell awakeFromNib方法而不是表视图cellForRowAt方法.将可重复使用cell的广告出现您的CustomCell上时,这是来自@LeoDabus的示例

  • @NazmulHasan你应该创建一个CustomCell子类化UITableViewCell并在UITableViewCell awakeFromNib方法中配置你的accessoryView而不是UITableViewController cellForRowAt方法.将可重复使用的单元格出列时,将其转换为CustomCell (2认同)