I'm trying to use UIImage's new withTintColor method to update images for dark mode. So far, it only works when using UIButton but not UIImageView nor CALayer.
As far as I can tell, accessing the cgImage never returns a tinted image. I also can't find an API on UIImage to see if it was created with a tint color. Is there an API I'm missing?
This is what I've tried so far:
let dynamicColor = UIColor(dynamicProvider: { (traitCollection) -> UIColor in
if traitCollection.userInterfaceStyle == .dark {
return UIColor.white
} else {
return UIColor.black
}
})
let pinkImage = #imageLiteral(resourceName: "PinkImage")
let hopefullyDynamicImage = pinkImage.withTintColor(dynamicColor, renderingMode: .alwaysOriginal)
// This UIButton properly shows a black or white image depending on dark mode. It automatically updates
someButton.setImage(hopefullyDynamicImage, for: .normal)
// This UIImageView shows either white or black image, but it doesn't update when the dark mode is switched on or off. It is stuck in time
someImageView.image = hopefullyDynamicImage
// This CALayer shows up as pink. The tint had no effect
someUIView.layer.contents = hopefullyDynamicImage.cgImage
I've also tried using UIImageConfiguration like this, but it still has no tint in the cgImage:
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
// This layer still shows no tint color. It is the original pink
someUIView.layer.contents = hopefullyDynamicImage?.withConfiguration(self.traitCollection.imageConfiguration).cgImage
}