迅速的明暗模式

问题描述 投票:0回答:1

我为黑暗和光明模式创建了图像资产,名为myImage。 将图像资产的外观设置为Any,Dark。

问题是即使模式是亮或暗,这段代码也会得到相同的图像。

我怎样才能让代码根据亮模式或暗模式选择正确的图像?

谢谢您的帮助。

let image = UIImage(named: "image")
let asset = image?.imageAsset
let resolvedImage =    asset?.image(with: traitCollection)

If let image = resolvedImage {
  myButton.setImage(image, for:     .normal)
}
swift light ios-darkmode
1个回答
0
投票

let image = UIImage(named: "image") 如果你正确设置了你的资产,通常只需要这样做。确保将 "外观 "设置为 "Any, Dark",然后在适当的插槽中添加图像。

enter image description here


0
投票

找出当前使用的暗光模式。

if traitCollection.userInterfaceStyle == .light {
    print("Light mode")
} else {
    print("Dark mode")
}

然后我会用不同的名字访问光暗模式的图像: UIImage:(命名为:"myImageLightMode") 和 UIImage:(命名为:"myImageDarkMode")

请记住,当你不想在不同的颜色上创建每个图标时,你可以像下面这样将按钮图像调成所需的颜色。

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

在UIImageView上也可以通过扩展来实现。

extension UIImageView {
    func setImageAndColor(image: UIImage, color: UIColor) {
        let templateImage = image.withRenderingMode(.alwaysTemplate)
        self.image = templateImage
        self.tintColor = color
    }
}

访问这个:

let imageView = UIImageView()
imageView.setImageAndColor(image: UIImage(named: "yourImage"), color: .red)
© www.soinside.com 2019 - 2024. All rights reserved.