This is a continuation of an earlier post. What I was wondering was how to add the user defaults for the dark mode throughout the app. Please do not pay attention for the code that says UserDefaults in my last post, I was following a tutorial and just kind of copied what he did, not knowing anything at all about User Defaults. The whole dark mode works beautifully throughout the app. I just need to know how to do all the user defaults. If you have any questions feel free to ask.
The code below is what the custom cell looks like below that is in a settings view controller, to change the app to a Dark Mode. Everything works great and as it should. I just need to put in the user defaults into the actions.
import UIKit
class DarkModeTableViewCell: UITableViewCell {
var DarkisOn = Bool()
let userDefaults = UserDefaults.standard
@IBOutlet var darkModeSwitchOutlet: UISwitch!
override func awakeFromNib() {
super.awakeFromNib()
NotificationCenter.default.addObserver(self, selector: #selector(darkModeEnabled(_:)), name: .darkModeEnabled, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(darkModeDisabled(_:)), name: .darkModeDisabled, object: nil)
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
@IBAction func darkModeSwitched(_ sender: Any) {
if darkModeSwitchOutlet.isOn == true {
//enable dark mode
DarkisOn = true
//add a userDefault here so that the app will stay in dark mode
NotificationCenter.default.post(name: .darkModeEnabled, object: nil)
} else {
//enable light mode
DarkisOn = false
//add a userDefault here so that the app will stay in light mode
NotificationCenter.default.post(name: .darkModeDisabled, object: nil)
}
}
@objc private func darkModeEnabled(_ notification: Notification) {
DarkModeTableViewCellChange.instance.set(for: self)
textLabel?.textColor = UIColor.white
}
@objc private func darkModeDisabled(_ notification: Notification) {
LightModeTableViewCellChange.instance.set(for: self)
textLabel?.textColor = UIColor.black
}
}
EDIT: What I am looking for is how to add the user defaults to the dark mode. So once the dark mode is turned on, then when you close the app, it would stay on, etc.