我在SwiftUI中创建了一个带有背景颜色的白色.background(Color.white)
的自定义工作表
现在,我希望当用户打开iOS上的黑暗模式时,背景色变为黑色。但我找不到一个动态的颜色为背景,如Color.primary
的颜色,文字等。
那么,当黑暗模式打开时,有没有办法将背景颜色更改为黑色呢?
发布于 2020-02-06 16:47:44
为了详细说明这两个现有的答案,有几种方法可以根据您想要实现的目标来根据光或暗模式(又名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))
}
如果要根据处于光或暗模式的设备自定义视图的颜色,可以这样做(根据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视图默认将其背景色设置为.systemBackground
,因此,如果您使用的是ScrollView、List、Form等,则它们将使用默认的系统背景色,除非您想要自定义,否则不需要使用.background
。
发布于 2020-06-05 02:50:02
如果您想要直接从Color
中工作的东西(就像您在Color.primary
中所做的那样),以及iOS和macOS上的函数(UIColor
不会在macOS上工作),您可以使用以下简单的Color
扩展,它使用条件编译来正确地在任何一个操作系统上工作。
然后,您只需像其他任何SwiftUI Color
一样,从代码的其他地方访问这些代码。例如:
let backgroundColor = Color.background
不需要用这种方法检查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
}
发布于 2020-01-11 13:06:23
将.background(Color.white)
更改为.background(Color(UIColor.systemBackground))
https://stackoverflow.com/questions/59694589
复制相似问题