在 SwiftUI 中,如果需要为某些子视图使用轻量级变体,则足以强制.colorScheme为其指定,如下所示
颜色变体:

演示:

var body: some View {
VStack {
Rectangle().fill(Color("testColor"))
.frame(width: 100, height: 100)
.environment(\.colorScheme, .light) // << force light
}
.frame(width: 300, height: 300)
.background(Color("testColor")) // << system appearance
}
Run Code Online (Sandbox Code Playgroud)
如果您正在使用 UIKit,那么UIColor的resolvedColor(with traitCollection:)方法是覆盖默认配色方案的方法。
如果你像我一样不喜欢在 SwiftUI 代码中看到 UIColors,下面是一种更 SwiftUI-y 的方法来获得相同的效果,到目前为止对我来说效果很好:
extension View {
@ViewBuilder
func forceDarkVariant(_ forceDark: Bool) -> some View {
if forceDark {
self.environment(\.colorScheme, .dark)
} else {
self
}
}
}
Run Code Online (Sandbox Code Playgroud)