5

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")!
}
Tom Kraina
  • 3,569
  • 1
  • 38
  • 58

2 Answers2

3

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.

Frank Rupprecht
  • 9,191
  • 31
  • 56
  • The problem I'm trying to solve is when I use a combination of .tertiarySystemBackground for cell's background and .opaqueSeparator for separators, the contrast between these two in .elevated mode is too subtle, making is impossible to notice the separators. – Tom Kraina Sep 20 '19 at 13:44
1

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
}
laka
  • 644
  • 8
  • 23