Skip to content

Instantly share code, notes, and snippets.

@akaDuality
Created March 11, 2022 04:29
Show Gist options
  • Save akaDuality/3851e034b5f0d6b4b2ca25076f374f51 to your computer and use it in GitHub Desktop.
Save akaDuality/3851e034b5f0d6b4b2ca25076f374f51 to your computer and use it in GitHub Desktop.
NSColor + Dark Mode
import AppKit
extension NSAppearanceCustomization {
@discardableResult
public func performWithEffectiveAppearanceAsDrawingAppearance<T>(
_ block: () -> T) -> T {
// Similar to `NSAppearance.performAsCurrentDrawingAppearance`, but
// works below macOS 11 and assigns to `result` properly
// (capturing `result` inside a block doesn't work the way we need).
let result: T
let old = NSAppearance.current
NSAppearance.current = self.effectiveAppearance
result = block()
NSAppearance.current = old
return result
}
}
extension NSColor {
/// Uses the `NSApplication.effectiveAppearance`.
/// If you need per-view accurate appearance, prefer this instead:
///
/// let cgColor = aView.performWithEffectiveAppearanceAsDrawingAppearance { aColor.cgColor }
public var effectiveCGColor: CGColor {
#if DEBUG
let isTesting = NSClassFromString("XCTest") != nil
if isTesting {
return cgColor
}
#endif
return NSApp.performWithEffectiveAppearanceAsDrawingAppearance {
self.cgColor
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment