问题
I created images assets for dark and light mode called myImage. Set the image assets appearance to Any, Dark.
The problem this code gets the same image even if the mode is light or dark.
How can I get the code to select the correct image depending on light or dark mode?
Thanks for your help.
let image = UIImage(named: "image")
let asset = image?.imageAsset
let resolvedImage = asset?.image(with: traitCollection)
If let image = resolvedImage {
myButton.setImage(image, for: .normal)
}
回答1:
let image = UIImage(named: "image")
is usually all that is needed, if you setup your asset correctly. Make sure to have "Appearances" set to "Any, Dark", then add your images in the appropriate slots:
回答2:
Find out the current used dark/light mode with:
if traitCollection.userInterfaceStyle == .light {
print("Light mode")
} else {
print("Dark mode")
}
Then I'd access the light/dark Images with different name: UIImage:(named: "myImageLightMode") and UIImage:(named: "myImageDarkMode")
Keep in mind that you can tint images like button images in the desired color like the following, when you don't want to create each icon on a different color:
if let originalImage = UIImage(named: "yourButtonImage") {
let tintedImage = originalImage.withRenderingMode(.alwaysTemplate)
customButton.setImage(tintedImage, for: .normal)
customButton.tintColor = UIColor.red
} else {
print("Image not found.")
}
The same can be done on UIImageView's with the extension:
extension UIImageView {
func setImageAndColor(image: UIImage, color: UIColor) {
let templateImage = image.withRenderingMode(.alwaysTemplate)
self.image = templateImage
self.tintColor = color
}
}
access this with:
let imageView = UIImageView()
imageView.setImageAndColor(image: UIImage(named: "yourImage"), color: .red)
来源:https://stackoverflow.com/questions/61972859/light-and-dark-mode-in-swift