Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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")!
}
like image 819
Tom Kraina Avatar asked Sep 20 '19 10:09

Tom Kraina


2 Answers

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.

like image 140
Frank Schlegel Avatar answered Nov 19 '22 08:11

Frank Schlegel


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
}
like image 41
laka Avatar answered Nov 19 '22 08:11

laka