Dynamic Color Theming with UIColor Extension
2 min readFeb 1, 2024
The provided Swift code is an extension on the UIColor
class in Swift, implementing dynamic color theming based on the user interface style (light or dark mode). The code is designed to work with color assets, such as those defined in an XCAssets file.
/// Basically returns a Color Set like we see in XCAssets
private static func colorSet(light: UIColor, dark: UIColor? = nil) -> UIColor {
UIColor { traitCollection -> UIColor in
switch traitCollection.userInterfaceStyle {
case .dark:
return dark?.resolveToLight() ?? light.resolveToLight()
case .light, .unspecified:
fallthrough
@unknown default:
return light.resolveToLight()
}
}
}
/// Returns the Light Appearance UIColor of the given SwiftGen color asset
private static func lightColorFrom(assetColor: AssetColorTypeAlias) -> UIColor {
let color: UIColor = assetColor
return color.resolveToLight()
}
/// Returns the current UIColor's Light Appearance
private func resolveToLight() -> UIColor {
resolvedColor(with: UITraitCollection(userInterfaceStyle: .light))
}
Functions:
colorSet(light:dark:)
function:
- This function takes two UIColor parameters,
light
anddark
(optional). - It returns a dynamic UIColor based on the current user interface style.
- Inside the closure, it uses a
traitCollection
to determine the current user interface style. - If the style is dark, it resolves to the
dark
color (or falls back to resolvinglight
to a light appearance ifdark
is not provided). - If the style is light or unspecified, it resolves to the
light
color.
lightColorFrom(assetColor:)
function:
- This function takes an
AssetColorTypeAlias
(presumably a color asset generated by SwiftGen) and converts it to aUIColor
. - It then calls the
resolveToLight()
method on the obtained color.
resolveToLight()
method:
- An instance method for
UIColor
that resolves the color to its light appearance. - It utilizes
resolvedColor(with:)
method with aUITraitCollection
set to light mode.
Usage:
- Developers can use
colorSet(light:dark:)
when defining dynamic colors, allowing the system to automatically choose the appropriate color based on the user interface style. - The
lightColorFrom(assetColor:)
function is provided for converting color assets to their light appearances. - The
resolveToLight()
method can be used on anyUIColor
instance to get its light appearance.
This code promotes code reusability and enhances the adaptability of the app’s color scheme to different system appearances. It is particularly useful when working with dynamic theming and ensuring a consistent visual experience across different UI styles.