How do I save the state of the switch. I have a switch in a custom cell. I have a class for the custom cell. I am trying to save it from a view controller.
class Settings_Custom_Cell: UITableViewCell {
@IBOutlet weak var settingLabel: UILabel!
@IBOutlet weak var quickAddSwitch: UISwitch!
}
class SettingsCell {
var settingLabel: String
var settingValue: UISwitch
init(settingLabel: String, settingValue: UISwitch) {
self.settingLabel = settingLabel
self.settingValue = settingValue
}
}
import UIKit
class Settings: UIViewController, UITableViewDelegate, UITableViewDataSource {
var array: [String] = ["Quick Add"]
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return array.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = table.dequeueReusableCell(withIdentifier: "cell", for: indexPath as IndexPath)
cell.textLabel?.text = ""
cell.textLabel?.text = array[indexPath.row]
cell.textLabel?.numberOfLines = 0
cell.textLabel?.lineBreakMode = NSLineBreakMode.byWordWrapping
cell.textLabel?.font = UIFont.systemFont(ofSize: 20)
return cell
}
@IBOutlet weak var table: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
}
}
I figured out how to save the state of the switch when the state of the switch is changed. Thanks for your help on getting me there.
class SettingsCustomCell: UITableViewCell {
//...
@IBAction func switchValueChanged(_ sender: UISwitch) {
state?.settingValue = sender.isOn
let defaults = UserDefaults.standard
defaults.set(quickAddSwitch.isOn, forKey: "quickAdd")
}
}
class Settings: UIViewController, UITableViewDelegate, UITableViewDataSource {
//...
override func viewDidLoad() {
super.viewDidLoad()
cellStates = [
SettingsState(settingLabel: "Quick Add", settingValue: (UserDefaults.standard.bool(forKey: "quickAdd")))
]
}
}