Skip to content

Instantly share code, notes, and snippets.

struct MyThemeSettings {
let appBgColor: UIColor
let highlightedBgColor: UIColor
let textColor: UIColor
}
let lightThemeModel = MyThemeModel(
appBgColor: .white,
textColor: .black)
let darkThemeModel = MyThemeModel(
appBgColor: .darkGray,
textColor: .white)
enum MyTheme {
case light
case dark
var settings: MyThemeSettings {
switch self {
case .light: return MyThemeSettings.lightTheme
case .dark: return MyThemeSettings.darkTheme
}
}
}
@objc protocol Themable {
func applyTheme(_ theme: MyTheme)
}
import Foundation
final class ThemeManager {
private var themables = NSHashTable<Themable>
.weakObjects()
var theme: MyTheme {
didSet {
guard theme != oldValue else { return; }
apply()
@objc enum MyTheme: Int {
    case light
    case dark
    var settings: MyThemeSettings {
        switch self {
        case .light: return MyThemeSettings.lightTheme
        case .dark: return MyThemeSettings.darkTheme
        }
    }
}
import UIKit
// MARK: - Highlighted Label Class
class HighlightedLabel: UILabel {
override func didMoveToWindow() {
// Subscribe to theme notifications
ThemeManager.shared.register(self)
super.didMoveToWindow()
}
}
import Foundation
fileprivate var associatedKey = "ThemerTargetActionStorage"
final class TargetActionStorage {
private var targetActions: [TargetAction] = []
static func setup(for target: Any) -> TargetActionStorage {
let storage = TargetActionStorage()
objc_setAssociatedObject(
protocol TargetAction {
func applyTheme(_ theme: MyTheme)
}
struct AnyTargetActionWrapper<T: AnyObject>: TargetAction {
weak var target: T?
let action: (T) -> (MyTheme) -> ()
func applyTheme(_ theme: MyTheme) -> () {
if let t = target {
import Foundation
final class ThemeManager {
private var targetActionStorages = NSHashTable<TargetActionStorage>
.weakObjects()
var theme: MyTheme {
didSet {
guard theme != oldValue else { return; }
apply()