【问题标题】:What is the Dynamic Provider equivalent for UIImages?UIImages 的动态提供程序等价物是什么?
【发布时间】:2020-07-15 23:24:23
【问题描述】:

我们可以使用动态提供程序来扩展 UIColor 类,并让颜色立即变为深色和浅色模式,就像这样

extension UIColor {
  static var myControlBackground: UIColor {
      return UIColor { (traits) -> UIColor in
        // Return one of two colors depending on light or dark mode
        return traits.userInterfaceStyle == .dark ?
          UIColor(red: 0.5, green: 0.4, blue: 0.3, alpha: 1) :
          UIColor(red: 0.3, green: 0.4, blue: 0.5, alpha: 1)
      }
  }
}

但是 UIImages 呢?

我知道你可以用这个方法

override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
  if traitCollection.hasDifferentColorAppearance(comparedTo:
                                                 previousTraitCollection) {
    // Color change detected.
    // Adjust the interface accordingly.
  }
}

问题在于,如果应用程序在发生更改时处于后台,则此方法不会检测到更改。颜色动态方法可以。

任何想法

【问题讨论】:

  • traitCollectionDidChange 在外观改变时如果应用程序处于后台,则不会检测到变化。
  • 我想知道我是否可以通过编程方式做到这一点,或者换句话说,不使用资产目录中的图像集。创建一种在外观发生变化时自动将图像更改为暗/亮等效物的方式。

标签: ios uiimage uicolor ios-darkmode


【解决方案1】:

您正在寻找 UIImageAsset 类:

https://developer.apple.com/documentation/uikit/uiimageasset

基本上,您为不同的 trait 集合制作一个图像资源以及 UIImage 的版本,并在图像资源上调用 register 以及图像及其相应的 trait 集合。

【讨论】:

  • 优秀。我一直在寻找相同的东西,但我想注册与我自己的主题相关的图像(不仅是深色或浅色,还包括万圣节主题)。我用颜色和动态提供者来做这件事,效果很好,但我不确定如何用图像来做这件事……如果可能的话,你知道@matt 吗?
  • @ernewston 您如何使用颜色和动态提供程序来做到这一点?您无法制作自定义特征(据我所知)。
  • var background = UIColor { _ in switch theme { case .light: return color1 case .dark: return color2 case .halloween: return color3 } }。我不为什么苹果将外观限制在两个,如果有 N 个自定义特征来处理主题会很棒......
  • @ernewston 啊,我明白了。好吧,那不是颜色“动态提供者”。您没有像 Apple 那样制作实时动态颜色。当你改变主题时,你的界面颜色不会像苹果那样神奇地改变;您刚刚创建了一个在调用它时返回颜色的方法。那里没什么特别的。所以你可以对你的图片做同样的事情。
  • @ernewston 但将主题更改为 .halloween 时不会。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-11
  • 2020-02-17
  • 1970-01-01
  • 2010-11-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多