【问题标题】:Light and dark mode in swiftswift中的明暗模式
【发布时间】:2020-09-10 08:19:49
【问题描述】:

我为名为 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)
}

【问题讨论】:

  • 你试过 just UIImage(named: "image") 没有所有图像资产的东西吗? UIImage 是一个聪明的班级。
  • 是的,我尝试了 UIImage(named: "image"),但它在深色或浅色模式下都找不到正确的图像。
  • 您能显示您的资产目录的屏幕截图吗?它在我的 Mac 上运行...

标签: swift light ios-darkmode


【解决方案1】:

let image = UIImage(named: "image") 通常是所有需要的,如果你正确设置你的资产。确保将“外观”设置为“任何、深色”,然后将您的图片添加到相应的插槽中:

【讨论】:

    【解决方案2】:

    找出当前使用的暗/亮模式:

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

    然后我将访问具有不同名称的明暗图像:UIImage:(named: "myImageLightMode") 和 UIImage:(named: "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)
    

    【讨论】:

      猜你喜欢
      • 2021-12-18
      • 2021-08-07
      • 1970-01-01
      • 2020-07-08
      • 2021-05-30
      • 2020-04-14
      • 2020-01-19
      • 2021-01-19
      • 2020-03-09
      相关资源
      最近更新 更多