Add switch in UITableView cell in Swift

2020-02-10 04:51发布

How can I embed a UISwitch programmatically in a tableView cell in Swift? I'm doing it like that

let shareLocationSwitch = UISwitch()
cell.accessoryView = shareLocationSwitch

1条回答
小情绪 Triste *
2楼-- · 2020-02-10 05:18

Here is way you can embed a UISwitch on a UITableView cell.

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
      }

here is switch call beck method

func switchChanged(_ sender : UISwitch!){

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

@LeoDabus Great! explanation.

Note: if your tableview may have more than one section then You should create a CustomCell subclassing UITableViewCell and configure your accessoryView inside UITableViewCell awakeFromNib method instead of table view cellForRowAt method. When dequeuing the reusable cell cast it to your CustomCell Here is sample from @LeoDabus

查看更多
登录 后发表回答