Light and dark mode in swift

冷暖自知 提交于 2021-02-05 12:22:10

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!