Programmatically detect dark mode in SwiftUI to display appropriate Image

狂风中的少年 提交于 2020-05-26 11:16:26

问题


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.

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?


回答1:


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.

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")
    }
}



回答2:


There's an @Environment variable.

@Environment (\.colorScheme) var colorScheme:ColorScheme

Here's how I use it to fill an empty Rectangle:

Rectangle().fill(Color.fillColor(for: colorScheme))


来源:https://stackoverflow.com/questions/57279700/programmatically-detect-dark-mode-in-swiftui-to-display-appropriate-image

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!