Home > Enterprise >  Swift color-set programatically - Return color based on device color mode
Swift color-set programatically - Return color based on device color mode

Time:10-22

I am trying to achieve the Xcode color-set programatically. Get the colour based on theme

var appThemeColor : Any {
    if UITraitCollection.current.userInterfaceStyle == .dark {
        return UIColor.DarkTheme.self
    } else {
        return UIColor.LightTheme.self
    }
}

extension UIColor {
    
    struct LightTheme {
        static let barDeselectedColor =  UIColor(white: 0, alpha: 0.1)
        static let appBackground = #colorLiteral(red: 0.9529411793, green: 0.6862745285, blue: 0.1333333403, alpha: 1)
    }
    
    struct DarkTheme {
        static let barDeselectedColor = UIColor(white: 0, alpha: 0.1)
        static let appBackground = #colorLiteral(red: 0.8078431487, green: 0.02745098062, blue: 0.3333333433, alpha: 1)
    }
}


class MainVC: UIViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = appThemeColor.appBackground
    }
}

Depending on the device color mode. should return the color

view.backgroundColor = appThemeColor.appBackground

how ever my implementation is not working as expected. Any suggestions much appreciated.

CodePudding user response:

There are a couple of simpler ways to do this;

You can define your colours using the dynamic provider initialiser:


struct MyTheme {
    
    private func isDark(_ traitCollection: UITraitCollection) -> Bool {
        return traitCollection.userInterfaceStyle == .dark
    }

    public var barDeselectedColor = UIColor { (traitCollection: UITraitCollection) -> UIColor in
        return self.isDark(traitCollection) ? UIColor(red: 0.8078431487, green: 0.02745098062, blue: 0.3333333433, alpha: 1) : UIColor(red: 0.9529411793, green: 0.6862745285, blue: 0.1333333403, alpha: 1)
    }

    /// etc
}

Then use it like

    self.someBar.backgroundColor = MyTheme().barDeselectedColor

The system will supply the current trait collection to your initialiser and you will get the correct color back.

Or you can add your colours to your asset catalog as dynamic colours and refer to them by name.

CodePudding user response:

you can simply assign the color to your label or view background using your color set add a color set in your Assets.xcassets name your color set e.g primary_color and set color value then use as you need e.g

self.titleLabel.textColor = UIColor(named: "primary_color")

or

self.yourView.backgroundColor = UIColor(named: "primary_color")

no need to check either mobile them is on dark mode or light this color set handle automatically the color you set in color set

  • Related