O2ThemeManager.swift 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. //
  2. // O2ThemeManager.swift
  3. // SwiftTheme
  4. //
  5. // Created by Gesen on 16/1/22.
  6. // Copyright © 2016年 Gesen. All rights reserved.
  7. //
  8. import Foundation
  9. public let ThemeUpdateNotification = "ThemeUpdateNotification"
  10. public enum ThemePath {
  11. case mainBundle
  12. case sandbox(Foundation.URL)
  13. public var URL: Foundation.URL? {
  14. switch self {
  15. case .mainBundle : return nil
  16. case .sandbox(let path) : return path
  17. }
  18. }
  19. public func plistPath(name: String) -> String? {
  20. switch self {
  21. case .mainBundle:
  22. return Bundle.main.path(forResource: name, ofType: "plist")
  23. case .sandbox(let path):
  24. let name = name.hasSuffix(".plist") ? name : name + ".plist"
  25. let url = path.appendingPathComponent(name)
  26. return url.path
  27. }
  28. }
  29. }
  30. @objc public final class O2ThemeManager: NSObject {
  31. @objc public static var animationDuration = 0.3
  32. @objc public fileprivate(set) static var currentTheme: NSDictionary?
  33. @objc public fileprivate(set) static var currentThemeIndex: Int = 0
  34. public fileprivate(set) static var currentThemePath: ThemePath?
  35. }
  36. public extension O2ThemeManager {
  37. @objc class func setTheme(index: Int) {
  38. currentThemeIndex = index
  39. NotificationCenter.default.post(name: Notification.Name(rawValue: ThemeUpdateNotification), object: nil)
  40. }
  41. class func setTheme(plistName: String, path: ThemePath) {
  42. guard let plistPath = path.plistPath(name: plistName) else {
  43. print("SwiftTheme WARNING: Can't find plist '\(plistName)' at: \(path)")
  44. return
  45. }
  46. guard let plistDict = NSDictionary(contentsOfFile: plistPath) else {
  47. print("SwiftTheme WARNING: Can't read plist '\(plistName)' at: \(plistPath)")
  48. return
  49. }
  50. self.setTheme(dict: plistDict, path: path)
  51. }
  52. class func setTheme(dict: NSDictionary, path: ThemePath) {
  53. currentTheme = dict
  54. currentThemePath = path
  55. NotificationCenter.default.post(name: Notification.Name(rawValue: ThemeUpdateNotification), object: nil)
  56. }
  57. }