如何根据 Swift 5 中的系统背景颜色选择颜色?

时间:2020-12-18 20:49:53

标签: swift view colors swiftui background

我目前正在与 SwiftUI Colors 合作。

问题:我有一个 Card Component 的背景颜色为 systemGray6。这适用于大多数视图(所有具有 systemBackground 背景颜色的视图)

但是,我有一些带有 Modal ViewstertiarySystemBackground。这不会改变 LightMode 中的任何内容,但会将 DarkMode 中的背景颜色更改为与 systemGray6 相同。结果,背景和卡片具有相同的颜色,卡片不再可见。

我目前的解决方案:

struct Card: View {
    var isInsideModal: Bool = false

    var body: some View {
        // Some Content
        .background(isInsideModal ? Color.systemGray6 : Color.systemGray5) // I added this in an Extension of Color
    }
}

问题:是否有可能在无需始终将所需的 Background Color 显式传递给 Card View 的情况下自动执行此行为?

感谢您的帮助。

1 个答案:

答案 0 :(得分:2)

您可以在 xcassets 文件夹中创建颜色集。它使您能够根据您的应用是在暗模式还是亮模式下运行来选择不同的外观。