Programmatically detect dark mode in SwiftUI to display appropriate Image

后端 未结 2 2158
余生分开走
余生分开走 2021-02-19 05:14

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

2条回答
  •  耶瑟儿~
    2021-02-19 06:15

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

提交回复
热议问题