SwiftUI:获取动态背景颜色(暗模式或亮模式)

The*_*eil 5 macos background colors ios swiftui

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

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

let textColor = Color.primary
Run Code Online (Sandbox Code Playgroud)

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

let backgroundColor = Color.??? // Not available
Run Code Online (Sandbox Code Playgroud)

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

The*_*eil 9

因此,目前似乎没有任何此类属性内置到 SwiftUI 的操作系统独立Color类中;然而,UIColorNSColor 对它提供访问器(iOS和MacOS的分别),并且可以使用这些旧的颜色对象初始化SwiftUIColor对象。

因此,您可以使用对 的简单扩展来实现您的需求Color,如下所示,它使用条件编译在任一操作系统上正常工作。

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

我还包括了“二级”和“三级”颜色,它们在 macOS 上有点主观,但如果需要,您可以随时将它们更改为其他一些NSColor属性。

斯威夫特 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
}
Run Code Online (Sandbox Code Playgroud)

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

let backgroundColor = Color.background
Run Code Online (Sandbox Code Playgroud)