[英]How to use dark mode color in light mode of SwiftUI App?
I'm writing an app in SwiftUI, and have no trouble with normal UI.我正在 SwiftUI 中编写一个应用程序,正常 UI 没有问题。 However, when a view's background is opposite to the app background color (eg use picture background), I need exactly what that color in the other color scheme.
但是,当视图的背景与应用程序的背景颜色相反时(例如使用图片背景),我需要的正是其他配色方案中的那种颜色。 For example, Apple Music's lyrics are always in dark mode behavior (white text color, and white background color when hover) no matter what system color scheme is.
例如,无论系统配色方案是什么,Apple Music 的歌词始终处于深色模式行为(白色文本颜色,悬停时白色背景颜色)。
I know this Apple Music one can be solved by adding another color in Assets.xcassets
, but it's just an example.我知道这个 Apple Music 可以通过在
Assets.xcassets
中添加另一种颜色来解决,但这只是一个例子。 What I need is to use light
or dark
of a color programatically.我需要的是以编程方式使用
light
或dark
。 For those colors have different hex in different color schemes, how can I use its other side of color?对于那些 colors 在不同的配色方案中有不同的十六进制,我该如何使用它的另一面颜色? Say, can I use the dark mode one of
Color.primary
in light mode?比如说,我可以在亮模式下使用
Color.primary
的暗模式之一吗?
I tried a lot solutions, but in vain.我尝试了很多解决方案,但都是徒劳的。 Firstly, I tried to attach
.preferredColorScheme()
to that view, but it eventually change color scheme of my whole app.首先,我尝试将
.preferredColorScheme()
附加到该视图,但它最终改变了我整个应用程序的配色方案。 Secondarily, I tried to convert a color into NSColor
or UIColor
, but there also no method defined in those two frameworks, at least I couldn't find.其次,我尝试将颜色转换为
NSColor
或UIColor
,但这两个框架中也没有定义方法,至少我找不到。 They all cannot work.他们都不能工作。 How can I achieve this?
我怎样才能做到这一点?
VStack {
Text("Hello") // where I want to use dark mode color (white one)
.foregroundColor(.primary)
}
.background(Color.brown)
.preferredColorScheme(.dark) // I tried here
I'm not sure if there is a way to do this with SwiftUI.Color
directly but we have an extension in our app like...我不确定是否有办法直接使用
SwiftUI.Color
执行此操作,但我们的应用程序中有一个扩展,例如...
extension UIColor {
public var lightVariant: UIColor {
resolvedColor(with: UITraitCollection(userInterfaceStyle: .light))
}
public var darkVariant: UIColor {
resolvedColor(with: UITraitCollection(userInterfaceStyle: .dark))
}
}
And then you could use it with something like...然后你可以将它与类似...
extension UIColor {
public var asColor: Color {
Color(self)
}
}
To do...去做...
UIColor(named: "primary").darkVariant.asColor
Or something like that.或类似的东西。
Or from a Color
to begin with...或者从
Color
开始...
UIColor(Color.primary).darkVariant.asColor
(You could create conveniences for this also.) (您也可以为此创造便利。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.