Skip to content

Instantly share code, notes, and snippets.

@revblaze
Created December 8, 2020 18:59
Show Gist options
  • Save revblaze/bfe9969093fe60b181e14995b4eadfbc to your computer and use it in GitHub Desktop.
Save revblaze/bfe9969093fe60b181e14995b4eadfbc to your computer and use it in GitHub Desktop.
Extension: Quickly return the macOS' current system appearance
extension NSView {
var hasDarkAppearance: Bool {
if #available(OSX 10.14, *) {
switch effectiveAppearance.name {
case .darkAqua, .vibrantDark, .accessibilityHighContrastDarkAqua, .accessibilityHighContrastVibrantDark:
return true
default:
return false
}
} else {
switch effectiveAppearance.name {
case .vibrantDark:
return true
default:
return false
}
}
}
}
@revblaze
Copy link
Author

revblaze commented Dec 8, 2020

Usage Example

if view.hasDarkAppearance {
  // macOS is in dark mode
} else {
  // macOS is in default (light) mode
}

Note: When macOS toggles between modes, there is a slight delay caused by the transition time. Due to this, there is a noticeable interval in which the hierarchy correctly updates NSView's effectiveAppearance value.

One example, that I've found to be particularly annoying, is with observing the system appearance change. Something like this:

DistributedNotificationCenter.default.addObserver(forName: .systemAppearanceDidChange,
                                                          object: nil, queue: OperationQueue.main) {
  [weak weakSelf = self] (notification) in
  weakSelf?.updateAppearance()
}

func updateAppearance() {
  let isDarkMode = view.hasDarkAppearance 
}

The issue here arises when the system appearance changes and updateAppearance() is called:

// view is transitioning from light to dark
isDarkMode = false
// view is transitioning from dark to light
isDarkMode = true

Just be aware of this. The change is not instantaneous and the effectiveAppearance.name has a slight delay before updating to its proper value.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment