Tom Kraina
Tom Kraina

Reputation: 3689

iOS13: How to specify color for elevated user interface level in the asset catalog

iOS 13 brings us UIUserInterfaceLevel, which can be either .base or .elevated. The system seems to automatically adjust colors provided to UIView when the elevated level is used in dark mode.

However, there seems to be no way how to manually specify the .elevated color in the asset catalog, or is it?

The only way how to do it seems to be via the new UIColor constructor:

UIColor.init { (traits) -> UIColor in
   traits.userInterfaceLevel == .elevated ? UIColor(named: "myColor-elevated")! : UIColor(named: "myColor")!
}

Upvotes: 5

Views: 1205

Answers (2)

laka
laka

Reputation: 796

My solution was to combine .xcassets with this trait-dependent initializer. For each color I created a color set with light and dark color and another color set that only contains the elevated color (for any variant).

Then I added an extension to UIColor. This extension provides easy access to all the colors throughout the app and contains the logic for selecting the right color.

extension UIColor {
    static let backgroundPrimary = UIColor { (trait) -> UIColor in
        switch (trait.userInterfaceStyle, trait.userInterfaceLevel) {
        case (.dark, .elevated):
            // For this color set you can set "Appearances" to "none"
            return UIColor(named: "backgroundPrimaryElevated") ?? .black
        default:
            // This color set has light and dark colors specified
            return UIColor(named: "backgroundPrimary") ?? .black
        }
    }
    // ... All the other colors
}

Upvotes: 1

Frank Rupprecht
Frank Rupprecht

Reputation: 10383

There is no way to do that with color assets, as far as I know.

When you use the system background and fill colors, iOS will automatically pick the "next higher" color when on an elevated level, i.e., .systemBackground becomes .secondarySystemBackground, etc.

Upvotes: 3

Related Questions