Global change of background color

Viewed 88

So the problem is that I make a global change of the background color. I made code for a button which is saving the background color via a key in UserDefaults, then I inserted view.backgroundColor in the viewDidLoad of the main screen, but it is changing the color only on that screen. How can I change it globally?

1 Answers

Create a subclass for UIViewController that has a notification observer for the background color change and make your view controllers the subclass of it. After that, put a notification post in the didSet block of your user defaults variable.

class CustomBgColorViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = UserPrefs.customBgColor

        NotificationCenter.default.addObserver(self, selector: #selector(shouldChangeBgColor), name: .shouldChangeBgColor, object: nil)
    }

    @objc fileprivate func shouldChangeBgColor() {
        view.backgroundColor = UserPrefs.customBgColor
    }
}

extension Notification.Name {
    static let shouldChangeBgColor = Notification.Name(rawValue: "shouldChangeBgColor")
}

struct UserPrefs {
    static var customBgColor: UIColor! {
        didSet {
            [...]

            NotificationCenter.default.post(name: .shouldChangeBgColor, object: nil)
        }
    }
}
Related