在SwiftUI中以编程方式检测暗模式以显示适当的图像 [英] Programmatically detect dark mode in SwiftUI to display appropriate Image

查看:190
本文介绍了在SwiftUI中以编程方式检测暗模式以显示适当的图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Assets.xcassets中,可以添加其他图像,这些图像将根据外观自动切换.这对于静态图像效果很好,但是我试图弄清楚如何对下载的图像执行此操作.

In Assets.xcassets, there is an ability to add additional images that will automatically switch based on the Appearances. This works well for static images but I'm trying to figure out how to do this for downloaded images.

有没有办法在初始化时设置Image的暗模式版本,还是SwiftUI中有一个函数可以让您检测当前外观是否为暗,以便可以提供其他图像URL?

Is there a way to either set the dark mode version of an Image on init or is there a function in SwiftUI that will allow you to detect whether the current appearance is dark so that a different image URL can be served?

推荐答案

您可以在任何视图中使用@Environment(\.colorScheme) var colorScheme: ColorScheme来获取设备是处于暗模式(.dark)还是亮模式(.light).使用该信息,您可以有条件地决定使用三元运算符轻松显示哪个图像.

You can use @Environment(\.colorScheme) var colorScheme: ColorScheme in any view to get whether the device is in dark mode (.dark) or light mode (.light). Using that information, you can conditionally decide which image to show easily with a ternary operator.

例如,如果您有一个名为"lightImage"的图像(用于亮模式)和一个"darkImage"(用于暗模式):

For example, if you have an image named "lightImage" for light mode and "darkImage" for dark mode:

@Environment(\.colorScheme) var colorScheme: ColorScheme

var body: some View {
    Button(action: {
        foo()
    }) {
        Image(colorScheme == .light ? "lightImage" : "darkImage")
    }
}

这篇关于在SwiftUI中以编程方式检测暗模式以显示适当的图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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