Last active
January 25, 2026 14:54
-
-
Save fxm90/fd217b463222afd6eabcb006fb26d92e to your computer and use it in GitHub Desktop.
Creates an instance of `UIColor`, that generates its color data dynamically based on the current `userInterfaceStyle`. Furthermore this method falls back to the `lightVariant` color for iOS versions prior to iOS 13.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // | |
| // UIColor+MakeDynamicColor.swift | |
| // | |
| // Created by Felix Mau on 22/09/19. | |
| // Copyright © 2019 Felix Mau. All rights reserved. | |
| // | |
| import Foundation | |
| extension UIColor { | |
| /// Creates a dynamic color that automatically adapts to the current user interface style. | |
| /// | |
| /// On iOS 13 and later, the returned color switches between the provided light and dark variants | |
| /// based on the current `UITraitCollection`. On earlier iOS versions, the light variant is used. | |
| /// | |
| /// - Parameters: | |
| /// - lightVariant: The color used in light mode and on iOS versions prior to iOS 13. | |
| /// - darkVariant: The color used in dark mode. | |
| /// | |
| /// - Returns: A `UIColor` that adapts to the current interface style. | |
| static func makeDynamicColor(lightVariant: UIColor, darkVariant: UIColor) -> UIColor { | |
| guard #available(iOS 13.0, *) else { | |
| // Prior to iOS 13 there was no dark-mode, so we`re gonna return the light variant. | |
| return lightVariant | |
| } | |
| return UIColor { traitCollection -> UIColor in | |
| traitCollection.userInterfaceStyle == .dark | |
| ? darkVariant | |
| : lightVariant | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment