gpt4 book ai didi

swiftui - 在SwiftUI中打开暗模式时更改背景颜色

转载 作者:行者123 更新时间:2023-12-03 07:36:53 25 4
gpt4 key购买 nike

我已经在SwiftUI中创建了一个自定义工作表,其背景颜色为白色.background(Color.white)
现在,我希望当用户在iOS上打开暗模式时将背景色更改为黑色。
但是我找不到像Color.primary这样的背景动态颜色作为文本颜色等。

那么当打开暗模式时,有什么方法可以将背景颜色更改为黑色吗?

最佳答案

为了详细说明现有的两个答案,有两种方法可以根据您要实现的目的,根据亮或暗模式(又称为colorScheme)进行背景更改。

如果将背景色设置为白色(因为这是默认的背景色),并且希望系统能够在用户切换为暗模式时更新它,请将.background(Color.white)更改为.background(Color(UIColor.systemBackground))(umayanga的回答)。

例如

// Use default background color based on light/dark mode

struct ContentView: View {
...
var body: some View {

// ... to any view
.background(Color(UIColor.systemBackground))

}

如果要基于处于亮或暗模式的设备自定义 View 的颜色,则可以执行此操作(来自Asperi的回答):
// Use custom background color based on light/dark mode

struct ContentView: View {
@Environment(\.colorScheme) var colorScheme

...
var body: some View {

// ... to any view
.background(colorScheme == .dark ? Color.black : Color.white)

}

请注意,许多SwiftUI View 默认将其背景色设置为 .systemBackground,因此,如果您使用的是ScrollView,List,Form等,它们将使用默认的系统背景色,除非您愿意,否则无需使用 .background。自定义它。

关于swiftui - 在SwiftUI中打开暗模式时更改背景颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59694589/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com