11

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
TAO
  • 180
  • 1
  • 1
  • 11
  • it is so simple and easy just create a variable as a UISwitch() and then call cell accesooryView with that you don't need to do many stuff to get there the code is already inside the question. – TAO Oct 31 '17 at 18:11
  • i just edit the question. thank you for your solutions. – TAO Jan 18 '18 at 12:01
  • why my question received -2 point, it was really simple and after i found a good solution i just send it and edit the question so no one get confuse. – TAO Jan 18 '18 at 12:20
  • is there any reason that i don't now about it ? – TAO Jan 18 '18 at 12:20

2 Answers2

38

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

Nazmul Hasan
  • 10,130
  • 7
  • 50
  • 73
  • anyone explain me please why you give me down voted. please leave a comment – Nazmul Hasan Oct 31 '17 at 15:37
  • i accept your answer and did not give you a vote or take any vote from you – TAO Oct 31 '17 at 15:39
  • 1
    Not my down vote but probably because a tableview may have more than one section. You shouldn't use tag property for this – Leo Dabus Oct 31 '17 at 16:29
  • @LeoDabus Right! I prefer delegate. in this question that is off topic. anyway would you share me for detect each row switch event instant tag property – Nazmul Hasan Oct 31 '17 at 16:34
  • 2
    @NazmulHasan You should create a CustomCell subclassing UITableViewCell and configure your accessoryView inside UITableViewCell awakeFromNib method instead of UITableViewController cellForRowAt method. When dequeuing the reusable cell cast it to your CustomCell – Leo Dabus Oct 31 '17 at 16:39
  • @LeoDabus Great! that's clean code. thank you so much your help. – Nazmul Hasan Oct 31 '17 at 16:44
  • 1
    @NazmulHasan https://www.dropbox.com/s/l25wk7vq7zsm3zp/TableView%20SwitchSample.zip?dl=1 – Leo Dabus Oct 31 '17 at 16:49
  • 1
    I have added sections to the sample so you can use as a reference in the future if needed https://www.dropbox.com/s/up4fp9plzyxtlii/TableView%20SwitchSample%202.zip?dl=1 – Leo Dabus Oct 31 '17 at 17:55
  • Also look at this article it may be useful too . https://stackoverflow.com/questions/34971329/uiswitch-added-to-uitableviewcell-multiple-times-when-scrolling-uitableview-sw – TAO Jan 18 '18 at 12:06
  • 1
    Why not just use tableview.indexPath(for: sender.superview) in switchChanged – the Reverend Dec 09 '18 at 17:30
0

if you update the array with 3 elements and refreshing the table using self.tableView.reloadData() (for example after 2 second) you can see that with Xcode13 the switch values will be swapped and the example doesn't work. I have similar issue with my App when Xcode has been released to 13. try this: https://drive.google.com/file/d/1_1HuI_JFIYusNmsdyekGBWXsGznneiQ7/view?usp=sharing

Andruino
  • 11
  • 4