I want to make my dark mode work across all view controllers at the same time using Swift on Xcode. How would I do that?

Viewed 766

This is the code for dark mode. It works on one view controller but I want to make it work across all view controllers simultaneously. How would I do that?

@IBAction func darkModeAction(_ sender: UISwitch) {
      if darkModeSwitch.isOn == true {
          view.backgroundColor = UIColor.white
      }
      else {
          view.backgroundColor = UIColor.black
      }
    }
2 Answers

You can decide if you want to set that configuration from a specific ViewController with a switch, or in all of them, but the important part is that you want to save that state across the app state, so would be great that when the user decide he wants the dark version, to save it in UserDefaults.

Then in each ViewController you want this option to work for you, you might want to define a base ViewController in which you apply this background color (or from Xcode11 also the iOS 13 default Dark Mode) depending on the value of the UserDefaults or you can do that through an extension UIViewController where you apply to any instance of UIViewController that background based on the state of the UserDefaults key you saved - but yeah, this is not really safe.

As an example to implement it the first way, with a BaseVC, you can follow the below implementation, so aproximatelly in a configuration viewcontroller (where you have the switcher to decide if you want dark or light) there could exists something like:

@IBAction func darkModeAction(_ sender: UISwitch) {
    UserDefaults.standard.set(darkModeSwitch.isOn, forKey: "prefs_is_dark_mode_on")
}

And in your BaseViewController could be something like:

class BaseViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        let isDarkOn = UserDefaults.standard.bool(forKey: "prefs_is_dark_mode_on") as? Bool ?? true
        if #available(iOS 13.0, *) {
            overrideUserInterfaceStyle = isDarkOn ? .dark : .light // this line works only from Xcode11
        } else {
            view.backgroundColor = isDarkOn ? UIColor.black : UIColor.white
        }
    }
}

And then in each viewcontroller you want to make the background color black or white depending that setting state you can just do:

class ViewControllerSample: BaseViewController {
     // do other things you want to do in this viewcontroller, the background color will be set automatically through the BaseVC
}
For ios 13 simple call in viewcontroller within viewDidLoad()   
 override func viewDidLoad(){
         super.viewDidLoad()
         // for dark mode
         overrideUserInterfaceStyle = .dark

 }

for light mode

  overrideUserInterfaceStyle = .light

for more concepts follow the more about dark mode

Related