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")!
}
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.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With