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
The way I achieve adding spacing between cells is to make numberOfSections = "Your array count" and make each section contains only one row. And then define headerView and its height.
Choose iOS -> Source -> Cocoa Touch Class. Name the class TableCiewController and make it a subclass of UITableViewController. Go to the TableViewController. swift file and declare the following array.
There are two main base ways to populate a tableview. The more popular is through Interface Building, using a prototype cell UI object. The other is strictly through code when you don't need a prototype cell from Interface Builder.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With