Is there a Swifty way to detect the background color of a window in SwiftUI on macOS, that would work reliably regardless of the current theme (Dark Mode or Light Mode)?
For example, if one were to make a solid rectangle that "blends in" with the window's background, which color would they use?
This answer suggests the use of NSColor.xxxBackgroundColor:
SwiftUI: Get the Dynamic Background Color (Dark Mode or Light Mode)
However, this doesn't quite work for me. Here's some test code (Xcode 12.5, Swift 5.4) that makes three rectangles of various NSColors. I am looking for the one that blends in with the background.
struct TestView: View {
var body: some View {
VStack(spacing: 20) {
Text("This text is on the default background")
HStack(spacing: 30) {
Text("windowBackgroundColor")
.frame(width: 200, height: 100)
.background(Color(NSColor.windowBackgroundColor))
Text("underPageBackgroundColor")
.frame(width: 200, height: 100)
.background(Color(NSColor.underPageBackgroundColor))
Text("textBackgroundColor")
.frame(width: 200, height: 100)
.background(Color(NSColor.textBackgroundColor))
}
}
.padding(20)
}
}
In Dark mode, it seems NSColor.underPageBackgroundColor matches the window's background.




