7

I recently developed app which is compatible with Dark mode.

And dark mode also works fine. Btw when I change from dark->light, light->dark mode from device, all colors change as expected except border color.

Let's say border color is black when light mode and white when dark mode and system setting is dark mdoe. When I change system setting to light mode and return to app, all border colors stay white which is supposed be black.

Has anyone ever faced this issue and could you please help me solve this problem? This is serious problem when I want to implement real-time theme update in app.

Thanks.

Ioan Moldovan
  • 2,272
  • 2
  • 29
  • 54

2 Answers2

29

Thanks to @KurtRevis, I finally managed to solve the problem.

You need to listen to traitCollectionDidChange. If you want to change borderColor when appearance changes, you need code something like this.

override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
   if #available(iOS 13.0, *) {
       if (traitCollection.hasDifferentColorAppearance(comparedTo: previousTraitCollection)) {
           // ColorUtils.loadCGColorFromAsset returns cgcolor for color name
           layer.borderColor = ColorUtils.loadCGColorFromAsset(colorName: "CellBorderColor")
       }
   }
}

Hope this helps others

Ioan Moldovan
  • 2,272
  • 2
  • 29
  • 54
1

Depending on your circumstance you could make use of UIColor(dynamicProvider:), especially if traitCollectionDidChange(_:) is not an option (e.g. in a UIButton extension). Whenever the dynamicProvider is called upon to deliver the title color, it gives us an opportunity to update our border color as well. The example below just updates the border color to match the title color, but any other color could be used.

extension UIButton {
    func applyLoginStyle() {
        let titleColorProvider = UIColor { [weak layer] traitCollection in
            let titleColor = UIColor(named: "myColor")!.resolvedColor(with: traitCollection)
            layer?.borderColor = titleColor.cgColor
            return titleColor
        }

        setTitleColor(titleColorProvider, for: .normal)
    }
}
zath
  • 1,044
  • 8
  • 13