0

I found this bit of code online to add a gradient to my project and it does add the gradient beautifully

let gradientLayer = CAGradientLayer()
    gradientLayer.frame = self.view.bounds
    gradientLayer.colors = [UIColor.systemBackground.cgColor, UIColor.systemGray2.cgColor]
    self.view.layer.insertSublayer(gradientLayer, at: 0)

However, the colors don't change when I change between dark and light mode. I'm not sure why this is happening since I am using dark mode compatible colors. If anyone knows how to fix that bug please let me know.

shant_01
  • 172
  • 1
  • 8

1 Answers1

1

When you use adaptive colors with CALayers, colors are not updating when switching appearance live in the app. You can solve this by making use of the traitCollectionDidChange(_:) method.

override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
    super.traitCollectionDidChange(previousTraitCollection)

    if #available(iOS 13.0, *),
        let hasUserInterfaceStyleChanged = previousTraitCollection?.hasDifferentColorAppearance(comparedTo: traitCollection),
        hasUserInterfaceStyleChanged {
        // update layer
    }
}
Omer Faruk Ozturk
  • 1,722
  • 13
  • 25
  • I tried that out but it doesn't seem to update every single time. At the moment I am doing the gradient layout in viewWillLayoutSubviews, then I added the code you provided right after. Any Ideas? – shant_01 Jun 13 '20 at 18:46