OK so I rewrote some code,
Thanks, that makes sense a little more than the original code.
But still, a few things:
Having UI elements as data would not be a good practice
You use textLabel although you define settingLabel in your custom cell
You may need to reflect the state of each switch to some sort of data source.
Please try something like this.
Prepare a custom cell which can reflect the changes of switch:
class SettingsCustomCell: UITableViewCell {
@IBOutlet weak var settingLabel: UILabel!
@IBOutlet weak var quickAddSwitch: UISwitch!
var state: SettingsState? {
didSet {
if let state = state {
settingLabel.text = state.settingLabel
quickAddSwitch.isOn = state.settingValue
}
}
}
override func awakeFromNib() {
quickAddSwitch.addTarget(self, action: #selector(switchValueChanged), for: .valueChanged)
}
@objc func switchValueChanged(sender: UISwitch) {
state?.settingValue = sender.isOn
}
}
class SettingsState {
var settingLabel: String
var settingValue: Bool
init(settingLabel: String, settingValue: Bool) {
self.settingLabel = settingLabel
self.settingValue = settingValue
}
}
And use it like this:
class Settings: UIViewController, UITableViewDelegate, UITableViewDataSource {
var cellStates: [SettingsState] = [
SettingsState(settingLabel: "Quick Add", settingValue: false),
]
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return cellStates.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = table.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! SettingsCustomCell
cell.state = cellStates[indexPath.row]
return cell
}
@IBOutlet weak var table: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
table.dataSource = self
// Load `cellStates` if you need it...
// (I could not find when you want to save it.)
}
}