SwiftUI:获取动态背景颜色(深色模式或浅色模式)

SwiftUI: Get the Dynamic Background Color (Dark Mode or Light Mode)

有没有办法系统地访问 SwiftUI 视图的标准动态背景颜色,无论用户是处于亮模式还是暗模式?

例如,我知道以下内容可用于获取主要(例如文本)颜色:

let textColor = Color.primary

...但我没有看到任何类似的背景颜色。

let backgroundColor = Color.??? // Not available

我正在寻找适用于 iOS 和 macOS 的东西。

因此目前似乎没有任何此类 属性 内置于 SwiftUI 的 OS-独立 Color class;但是,UIColorNSColor do 为它提供访问器(分别在 iOS 和 macOS 上),您可以使用这些用于初始化 SwiftUI Color 对象的旧颜色对象。

因此,您可以使用 Color 的简单扩展来实现您的需求,如下所示,它使用条件编译在 OS.[=21= 上正常工作]

使用此方法无需检查 colorSchemeuserInterfaceStyle:当用户在明暗模式之间切换时,OS 将自动切换。

我还包括了 'secondary' 和 'tertiary' 颜色,这在 mac 上有点主观OS,但您可以随时将它们更改为其他颜色 NSColor属性,如果你想要的话。

Swift v5.2:

import SwiftUI

public extension Color {

    #if os(macOS)
    static let background = Color(NSColor.windowBackgroundColor)
    static let secondaryBackground = Color(NSColor.underPageBackgroundColor)
    static let tertiaryBackground = Color(NSColor.controlBackgroundColor)
    #else
    static let background = Color(UIColor.systemBackground)
    static let secondaryBackground = Color(UIColor.secondarySystemBackground)
    static let tertiaryBackground = Color(UIColor.tertiarySystemBackground)
    #endif
}

然后您只需像访问任何其他代码一样从代码中的其他地方访问它们 SwiftUI Color。例如:

let backgroundColor = Color.background