Search code examples
iosswiftuitableviewuiswitch

Adding a switch to each cell in a UItableview


I am building a settings page for my flashcard app. I have gotten to the point where when I run the tableview in the simulator It displays all the different categories that I have in the "setting" variable (shown in code below). However, I want to have a switch in each row that is created. For example if you look at the code the first row that is created is called "sound effects". There will be a switch in that row that will allow the user to turn the sound effects on and off. I am not asking how to add functionality to the switch (although if you can explain that it would be appreciated) but right now I am just concerned with creating a switch in each row thats created. Thank you!

import UIKit

class ThirdViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

var setting = ["Sound Effects", "initial /l/ 1 syllable", "initial /l/ multisyllabic", "intersyllabic /l/", "final /l/", "initial /pl/", "initial /bl/", "initial /fl/", "initial /gl/", "initial /kl/", "initial /sl/", "final /l/ clusters"]



@IBOutlet weak var tableView: UITableView!

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return (setting.count)
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = UITableViewCell()
    print(indexPath.row)
    cell.textLabel?.text = setting[indexPath.row]
    return cell
}



override func viewDidLoad() {
    super.viewDidLoad()

    tableView.dataSource = self
    tableView.delegate = self



}



}

Solution

  • You need to:

    1. Create a custom UITableViewCell subclass that has @IBOutlets for your text label and UISwitch.
    2. In your table view's storyboard or xib, set the type of the dynamic table view cell to the name of your custom subclass.
    3. In the cell's Attributes inspector, give it a custom reuse identifier.
    4. Drag a UISwitch into the dynamic cell prototype.
    5. Connect the custom cell's outlets to the text label and switch.
    6. In your tableView(_:cellForRowAt:) implementation, instead of instantiating a table cell each time (which is almost never what you want to do), call tableView.dequeueReusableCell(withIdentifier:for:) and pass in the custom reuse identifier that you used in step 3. Cast the returned cell to your custom type, then set the values of the outlets.