简体   繁体   中英

Global change of background color

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?

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)
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM