Skip to content

Instantly share code, notes, and snippets.

@mjmsmith
Last active February 4, 2023 21:36
Show Gist options
  • Save mjmsmith/30e95d3339a0a17d9bf8942627d955d2 to your computer and use it in GitHub Desktop.
Save mjmsmith/30e95d3339a0a17d9bf8942627d955d2 to your computer and use it in GitHub Desktop.
Resolve dynamic colors on macOS and iOS.
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