有没有办法系统地访问 SwiftUI View 的标准动态背景颜色,而不管用户是处于明模式还是暗模式?
例如,我知道以下内容可用于获取主要(例如文本)颜色:
let textColor = Color.primary
...但我没有看到任何类似的获得背景颜色的东西。
let backgroundColor = Color.??? // Not available
我正在寻找适用于 iOS 和 macOS 的东西。
最佳答案
因此,目前似乎没有任何此类属性内置到 SwiftUI 的操作系统独立 Color
中。类(class);然而,UIColor
和 NSColor
为它提供访问器(分别在 iOS 和 macOS 上),您可以使用这些旧的颜色对象来初始化 SwiftUI Color
目的。
因此,您可以使用对 Color
的简单扩展来实现您的需求。 ,如下所示,它使用条件编译在任一操作系统上正常工作。
无需查colorScheme
或 userInterfaceStyle
使用这种方法:当用户在明暗模式之间切换时,操作系统将自动切换。
我还包含了“二级”和“三级”颜色,它们在 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/