Advertisement
Guest User

Untitled

a guest
Mar 22nd, 2019
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.60 KB | None | 0 0
  1. import UIKit
  2. import Foundation
  3. import PlaygroundSupport
  4.  
  5. enum Theme {
  6. case light
  7. case dark
  8.  
  9. var description: String {
  10. switch self {
  11. case .light: return "Light"
  12. case .dark: return "Dark"
  13. }
  14. }
  15. }
  16.  
  17. extension Notification.Name {
  18. static let themeChanged = Notification.Name("themeChanged")
  19. }
  20.  
  21. // Dependency injection
  22. //final class ThemeManager {
  23. // private(set) var theme: Theme = .light {
  24. // didSet {
  25. // NotificationCenter.default.post(name: .themeChanged, object: nil)
  26. // }
  27. // }
  28. //
  29. // func changeTheme(to theme: Theme) {
  30. // self.theme = theme
  31. // }
  32. //}
  33.  
  34.  
  35. // Singleton
  36. final class ThemeManager {
  37.  
  38. static let current = ThemeManager()
  39.  
  40. private(set) var theme: Theme = .light {
  41. didSet {
  42. NotificationCenter.default.post(Notification(name: .themeChanged))
  43. }
  44. }
  45.  
  46. private init() {}
  47.  
  48. func changeTheme(to theme: Theme) {
  49. self.theme = theme
  50. }
  51. }
  52.  
  53. final class ViewController: UIViewController {
  54.  
  55. override func viewDidLoad() {
  56. super.viewDidLoad()
  57. self.applyTheme()
  58. NotificationCenter.default.addObserver(self, selector: #selector(self.applyTheme), name: .themeChanged, object: nil)
  59.  
  60. DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
  61. ThemeManager.current.changeTheme(to: .dark)
  62. }
  63. }
  64.  
  65. @objc
  66. private func applyTheme() {
  67. let theme = ThemeManager.current.theme
  68. print(theme.description)
  69. }
  70. }
  71.  
  72. let viewController = ViewController()
  73. PlaygroundPage.current.liveView = viewController
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement