在 SwiftUI 中打开暗模式时更改背景颜色 [英] Change background color when dark mode turns on in SwiftUI

查看:57
本文介绍了在 SwiftUI 中打开暗模式时更改背景颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 SwiftUI 中创建了一个自定义工作表,背景颜色为白色 .background(Color.white)

I've created a custom sheet in SwiftUI with the background color White .background(Color.white)

现在我希望当用户在 iOS 上打开暗模式时背景颜色变为黑色.但是我找不到像 Color.primary 这样的背景的动态颜色,用于文本的颜色等.

Now I want the background color to change to black when the user turns on the dark mode on iOS. But I can't find a dynamic color for background like Color.primary for colors of the text etc.

那么有没有什么办法可以在开启深色模式时将背景颜色更改为黑色?

So is there any way to change the background color to black when dark mode turns on?

推荐答案

为了详细说明现有的两个答案,有几种方法可以根据浅色或深色模式(又名 colorScheme) 取决于您要实现的目标.

To elaborate on the two existing answers, there are a couple of approaches to making the background change based on light or dark mode (aka colorScheme) depending on what you're trying to achieve.

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

If you set the background color to white because that's the default background color, and you want the system to be able to update it when the user switches to dark mode, change .background(Color.white) to .background(Color(UIColor.systemBackground)) (umayanga's answer).

例如

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

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

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

}

如果您想根据设备处于明暗模式自定义视图的颜色,您可以这样做(来自 Asperi 的回答):

If you want to customize the color of a view based on the device being in light or dark mode, you can do this (from Asperi's answer):

// 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 视图将其背景颜色设置为 .systemBackground,因此如果您使用的是 ScrollView、List、Form 等,它们将使用默认系统背景颜色并且除非你想自定义它,否则你不需要使用 .background.

Note that many SwiftUI views set their background color to .systemBackground by default, so if you're using a ScrollView, List, Form, etc, they'll use the default system background color and you won't need to use .background unless you want to customize it.

这篇关于在 SwiftUI 中打开暗模式时更改背景颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆