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
}
}
You need to:
UITableViewCell
subclass that has @IBOutlet
s for your text label and UISwitch
.UISwitch
into the dynamic cell prototype. 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.