Xcode 11 — SwiftUI's dark mode setup

前端 未结 3 1637
感动是毒
感动是毒 2021-01-04 15:14

Okay. I know this shouldn\'t be rocket science. I can\'t seem to get dark mode working and I\'ve read the documentation a few times. Hoping someone can pick out what I\'m

3条回答
  •  离开以前
    2021-01-04 16:10

    A working (but quite verbose) solution we can use to overcome this current limitation is to extend Color with methods parameterised with the current color scheme as follows:

    import SwiftUI
    
    extension Color {
    
        static let lightBackgroundColor = Color(white: 1.0)
    
        static let darkBackgroundColor = Color(white: 0.0)
    
        static func backgroundColor(for colorScheme: ColorScheme) -> Color {
            if colorScheme == .dark {
                return darkBackgroundColor
            } else {
                return lightBackgroundColor
            }
        }
    }
    

    And in the views where you need to access these colors you would add an environment property for the color scheme and use it to retrieve the dynamic color:

    import SwiftUI
    
    struct ColoredView : View {
    
        @Environment(\.colorScheme) var colorScheme: ColorScheme
    
        var body: some View {
            Rectangle().fill(Color.backgroundColor(for: self.colorScheme))
        }
    }
    

    These colours defined in code work for Xcode previews as well as the simulator.

提交回复
热议问题