Created
March 11, 2022 04:29
-
-
Save akaDuality/3851e034b5f0d6b4b2ca25076f374f51 to your computer and use it in GitHub Desktop.
NSColor + Dark Mode
This file contains 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 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