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

标签 ios macos colors background swiftui

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

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

let textColor = Color.primary

...但我没有看到任何类似的获得背景颜色的东西。
let backgroundColor = Color.??? // Not available

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

最佳答案

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

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

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

我还包含了“二级”和“三级”颜色,它们在 macOS 上有点主观,但您可以随时将它们更改为其他颜色 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

关于ios - SwiftUI:获取动态背景颜色(暗模式或亮模式),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60672626/

相关文章:

ios - "Present Modally"当另一个模式已经出现时不显示

ios - Swift:如何注销保留对象数?

ios - 如何共享个人 Apple iOS 开发者帐户

macos - 使用 Mac OS X 应用程序部署 GStreamer 框架的最佳方式?

objective-c - 沙盒 Mac 应用程序可以在哪里保存文件?

ios - corebluetooth 和 ios 状态

algorithm - 给定颜色和 alpha,添加什么颜色和 alpha 来创建所需的颜色?

用于打印 bash 颜色的 python 类

html - css:为什么不推荐使用 **color:red**?

macos - 从 USB 合成器读取音频