SwiftUI - How do I check to see if dark mode is enabled?

后端 未结 4 539
太阳男子
太阳男子 2020-12-22 05:36

How do I check to see if dark mode on the device is enabled. I want to check this from within a view and conditionally show or hide a shadow.

I thought I could jus g

4条回答
  •  余生分开走
    2020-12-22 06:02

    In my code, I have a simple View extension, that makes the code a lot more readable. With it, I can apply modifiers conditionally:

    .conditionalModifier(self.colorScheme == .light, LightShadow())
    

    The full implementation is below:

    extension View {
        // If condition is met, apply modifier, otherwise, leave the view untouched
        public func conditionalModifier(_ condition: Bool, _ modifier: T) -> some View where T: ViewModifier {
            Group {
                if condition {
                    self.modifier(modifier)
                } else {
                    self
                }
            }
        }
    }
    
    struct FloatingAddButton : View {
    
        @Environment(\.colorScheme) var colorScheme
    
        @Binding var openAddModal: Bool
    
        var body : some View {
            VStack {
                Spacer()
                HStack() {
                    Spacer()
                    Button(action: { self.openAddModal = true }) {
    
                        ZStack {
                            Circle()
                                .foregroundColor(Color(.red))
                                .frame(width: 50, height: 50, alignment: .center)
                                .conditionalModifier(self.colorScheme == .light, LightShadow())
    
                            Image(systemName: "plus")
                                .foregroundColor(Color.white)
                        }
                    }
    
                } // End Button
    
            }
        }
    }
    
    struct LightShadow: ViewModifier {
        func body(content: Content) -> some View {
            content.shadow(color: .secondary, radius: 5, x: 0, y: 0)
        }
    }
    

    If you ever have a case where you want to apply different modifiers for true and false, here's another extension:

    extension View {
        // Apply trueModifier if condition is met, or falseModifier if not.
        public func conditionalModifier(_ condition: Bool, _ trueModifier: M1, _ falseModifier: M2) -> some View where M1: ViewModifier, M2: ViewModifier {
            Group {
                if condition {
                    self.modifier(trueModifier)
                } else {
                    self.modifier(falseModifier)
                }
            }
        }
    }
    

提交回复
热议问题