Search code examples
iosuiimageuicolorios-darkmode

What is the Dynamic Provider equivalent for UIImages?


We can use dynamic providers to extent UIColor classes and have colors that change immediately to dark and light modes, like this

extension UIColor {
  static var myControlBackground: UIColor {
      return UIColor { (traits) -> UIColor in
        // Return one of two colors depending on light or dark mode
        return traits.userInterfaceStyle == .dark ?
          UIColor(red: 0.5, green: 0.4, blue: 0.3, alpha: 1) :
          UIColor(red: 0.3, green: 0.4, blue: 0.5, alpha: 1)
      }
  }
}

But what about UIImages?

I know that you can use this method

override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
  if traitCollection.hasDifferentColorAppearance(comparedTo:
                                                 previousTraitCollection) {
    // Color change detected.
    // Adjust the interface accordingly.
  }
}

the problem is that this method doe not detect changes if the app is in background when the change occurs. And the color dynamic method does.

Any ideas


Solution

  • You are looking for the UIImageAsset class:

    https://developer.apple.com/documentation/uikit/uiimageasset

    Basically, you make an image asset along with versions of the UIImage for different trait collections, and call register on the image asset with the image along with its corresponding trait collection.