How to check dark mode in AppKit for macOS apps
Issue #693
AppKit
app has its theme information stored in UserDefaults key AppleInterfaceStyle
, if is dark, it contains String Dark
.
Another way is to detect appearance via NSView
1 | struct R { |
Another way is to rely on appearance
on NSView. You can quickly check via NSApp.keyWindow?.effectiveAppearance
but notice that keyWindow
can be nil when the app is not active since no window is focused for keyboard events. You should use NSApp.windows.first
1 | let isDark = NSApp.windows.first?.effectiveAppearance.bestMatch(from: [.darkAqua, .vibrantDark]) == .darkAqua |
Then build a simple Theme system
1 | import SwiftUI |
For SwiftUI, you can colorScheme
environment, then use modifier .id(colorScheme)
to force SwiftUI to update when color scheme changes
1 | struct MainView: View { |
Updated at 2020-11-10 05:52:33