简体   繁体   English

swift中的明暗模式

[英]Light and dark mode in swift

I created images assets for dark and light mode called myImage.我为名为 myImage 的深色和浅色模式创建了图像资产。 Set the image assets appearance to Any, Dark.将图像资产外观设置为 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?如何根据亮或暗模式获取正确图像的 select 代码?

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)
}

let image = UIImage(named: "image") is usually all that is needed, if you setup your asset correctly.如果您正确设置资产,通常只需要let image = UIImage(named: "image")即可。 Make sure to have "Appearances" set to "Any, Dark", then add your images in the appropriate slots:确保将“外观”设置为“任何,深色”,然后将图像添加到相应的插槽中:

在此处输入图像描述

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")然后我将访问具有不同名称的亮/暗图像: UIImage:(named: "myImageLightMode") 和 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:在 UIImageView 上也可以使用扩展名进行同样的操作:

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM