Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import UIKit
- import Foundation
- import PlaygroundSupport
- enum Theme {
- case light
- case dark
- var description: String {
- switch self {
- case .light: return "Light"
- case .dark: return "Dark"
- }
- }
- }
- extension Notification.Name {
- static let themeChanged = Notification.Name("themeChanged")
- }
- // Dependency injection
- //final class ThemeManager {
- // private(set) var theme: Theme = .light {
- // didSet {
- // NotificationCenter.default.post(name: .themeChanged, object: nil)
- // }
- // }
- //
- // func changeTheme(to theme: Theme) {
- // self.theme = theme
- // }
- //}
- // Singleton
- final class ThemeManager {
- static let current = ThemeManager()
- private(set) var theme: Theme = .light {
- didSet {
- NotificationCenter.default.post(Notification(name: .themeChanged))
- }
- }
- private init() {}
- func changeTheme(to theme: Theme) {
- self.theme = theme
- }
- }
- final class ViewController: UIViewController {
- override func viewDidLoad() {
- super.viewDidLoad()
- self.applyTheme()
- NotificationCenter.default.addObserver(self, selector: #selector(self.applyTheme), name: .themeChanged, object: nil)
- DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
- ThemeManager.current.changeTheme(to: .dark)
- }
- }
- @objc
- private func applyTheme() {
- let theme = ThemeManager.current.theme
- print(theme.description)
- }
- }
- let viewController = ViewController()
- PlaygroundPage.current.liveView = viewController
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement