Last active
February 4, 2023 21:36
-
-
Save mjmsmith/30e95d3339a0a17d9bf8942627d955d2 to your computer and use it in GitHub Desktop.
Resolve dynamic colors on macOS and iOS.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import SwiftUI | |
// MARK: - macOS | |
#if os(macOS) | |
typealias OSColor = NSColor | |
extension OSColor { | |
func resolvedOSColor(colorScheme: ColorScheme? = nil) -> OSColor { | |
var currentCGColor: CGColor = cgColor | |
let appearance: NSAppearance? = { | |
guard let colorScheme else { | |
return nil | |
} | |
return NSAppearance(named: colorScheme == .dark ? .darkAqua : .aqua) | |
}() | |
(appearance ?? NSAppearance.currentDrawing()).performAsCurrentDrawingAppearance { | |
currentCGColor = cgColor | |
} | |
return OSColor(cgColor: currentCGColor) ?? .clear | |
} | |
} | |
#endif | |
// MARK: - iOS | |
#if os(iOS) | |
typealias OSColor = UIColor | |
extension OSColor { | |
func resolvedOSColor(colorScheme: ColorScheme? = nil) -> OSColor { | |
let traitCollection: UITraitCollection? = { | |
guard let colorScheme else { | |
return nil | |
} | |
return UITraitCollection(userInterfaceStyle: colorScheme == .dark ? .dark : .light) | |
}() | |
return resolvedColor(with: traitCollection ?? UITraitCollection.current) | |
} | |
} | |
#endif |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment