1

I've set up a dynamic UIColors for OS13 in my Swift app to handle dark mode.

For example:

static var background: UIColor {
    if #available(iOS 13, *) {
        return UIColor { (traitCollection: UITraitCollection) -> UIColor in
            if traitCollection.userInterfaceStyle == .dark {
                return UIColor(hex: "2b2d42")
            } else {
                return UIColor(hex: "FFFFFF")
            }
        }
    } else {
        return UIColor(hex: "FFFFFF")
    }
}

And wherever in code CGColor is used instead of UIColor I was planning to call traitCollectionDidChange of that particular UIView like this for example:

override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
    layer.fillColor = color.cgColor
}

It works but what I noticed is, that after changing the mode in settings if I use bottom swipe gesture to switch back to my app, then I can see all the UIColors already updated on the incoming screen, but the CGColors get updated only when app actually comes to foreground and traitCollectionDidChange is called.

enter image description here

Is there a better approach to this, so that the CGColors also get updated immediately?

Mahmut Acar
  • 713
  • 2
  • 7
  • 26
Matej Ukmar
  • 2,157
  • 22
  • 27
  • May be this will be helpful : https://stackoverflow.com/questions/56487679/how-do-i-easily-support-light-and-dark-mode-with-a-custom-color-used-in-my-app – Kishan Bhatiya Dec 19 '19 at 11:52

2 Answers2

1

go to Xcode > Assets.xcassets > new Color Set > set color for Light and Dark Appearance

now set this color in view background color

self.view.backgroundColor = UIColor.init(named: "ColorForCameraScreen")

enter image description here

  • Hi! Welcome to StackOverflow! You can use [formatting help](https://stackoverflow.com/editing-help#comment-formatting) to inline your image. – Lapshin Dmitry Dec 19 '19 at 12:14
  • 1
    I have a problem with the color of the logo, the background gets set correctly since it uses `UIColor` with dynamic provider, the problem is with logo where color is set with `CGColor` not `UIColor` – Matej Ukmar Dec 19 '19 at 13:48
0

Unfortunately, yes, this is your only choice.

CGColor is a CoreGraphics primitive, a plain static C struct which doesn't benefit from new UIColor dynamism capabilities.

However, in recent versions of iOS (I am testing on 15.0), your CGColors should be updated correctly in the App Switcher.

You can find more details in this article by jessesquires and in this other answer.

I hope this (late) answer helps shed some light on this.

Zedenem
  • 2,479
  • 21
  • 23