Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle custom colors for Dark Mode in Swift

Here is how I'm currently handling UI Element Colors for Dark Mode with a fallback for older operating systems.

extension UIColor {
    class var mySystemBackground: UIColor {
        if #available(iOS 13, *) {
            return .systemBackground
        } else {
            return .white
        }
    }
}

On this casesystemBackground knows when it's in Dark Mode and when it's in Light Mode and it changes accordingly. I would like to do something similar using custom colors.

For instance I have a custom Yellow color that I'm currently using throughout my app and I would like to provide a different color for when in Dark Mode.

Here is the code I'm thinking...

extension UIColor{
    class var mySystemYellowColor: UIColor {
        // default light-color 
        var myYellow = UIColor(red: 254/255, green: 219/255, blue: 2/255, alpha: 1.0) /* #fedb02 */

        if #available(iOS 13.0, *) {  

            if traitCollection.userInterfaceStyle == .light {
                return myYellow
            } else {
                // color for dark mode in iOS 13.0
                myYellow = UIColor(red: 242/255, green: 125/255, blue: 0/255, alpha: 1.0) /* #f27d00 */
            }
            return myYellow

        } else {
            return myYellow
        }
    }
}

Is this an approachable way to handle custom colors for Dark Mode in iOS13 with a fallback for other operating systems?

like image 841
fs_tigre Avatar asked Oct 29 '25 17:10

fs_tigre


1 Answers

Create the colors in the asset catalog.

Colors in the asset catalog can be created for different Appearances and can be accessed with the UIColor(named:) API

Please see Supporting Dark Mode in Your Interface

like image 182
vadian Avatar answered Oct 31 '25 06:10

vadian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!