简体   繁体   中英

SwiftUI: Get the Dynamic Background Color (Dark Mode or Light Mode)

Is there a way to systematically access the standard, dynamic background color for SwiftUI views, regardless of whether the user be in Light or Dark Mode?

For example, I know the following can be used to get the primary (eg text) color:

let textColor = Color.primary

...but I don't see anything similar for getting the background color.

let backgroundColor = Color.??? // Not available

I'm looking for something that works on both iOS and macOS.

So there doesn't currently appear to be any such property built into SwiftUI's OS-independent Color class; however, UIColor and NSColor do provide accessors for it (on iOS and macOS respectively), and you can use these older color objects to initialize a SwiftUI Color object.

As a result, what you need can be achieved using a simple extension to Color , such as the below, which uses conditional compilation to work correctly on either OS.

No need to check colorScheme or userInterfaceStyle with this approach: The OS will switch automatically when the user moves between Light & Dark mode.

I've also included 'secondary' & 'tertiary' colors, which are a little subjective on macOS, but you can always change them to some of the other NSColor properties if you want.

Swift v5.2:

import SwiftUI

public extension Color {

    #if os(macOS)
    static let background = Color(NSColor.windowBackgroundColor)
    static let secondaryBackground = Color(NSColor.underPageBackgroundColor)
    static let tertiaryBackground = Color(NSColor.controlBackgroundColor)
    #else
    static let background = Color(UIColor.systemBackground)
    static let secondaryBackground = Color(UIColor.secondarySystemBackground)
    static let tertiaryBackground = Color(UIColor.tertiarySystemBackground)
    #endif
}

You then simply access these from elsewhere in your code like any other SwiftUI Color . For example:

let backgroundColor = Color.background

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM