作者:拥有一YY_373 | 来源:互联网 | 2022-10-21 17:32
假设我的应用程式中有自订颜色:
extension UIColor {
static var myControlBackground: UIColor {
return UIColor(red: 0.3, green: 0.4, blue: 0.5, alpha: 1)
}
}
我在自定义控件(和其他地方)中使用它作为控件的背景:
class MyControl: UIControl {
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
setup()
}
private func setup() {
backgroundColor = .myControlBackground
}
// Lots of code irrelevant to the question
}
对于iOS 13,我希望我的自定义控件同时支持亮模式和暗模式。
一种解决方案是覆盖traitCollectionDidChange
并查看颜色是否已更改,然后根据需要更新我的背景。我还需要提供浅色和深色。
因此,我更新了自定义颜色:
extension UIColor {
static var myControlBackgroundLight: UIColor {
return UIColor(red: 0.3, green: 0.4, blue: 0.5, alpha: 1)
}
static var myControlBackgroundDark: UIColor {
return UIColor(red: 0.4, green: 0.3, blue: 0.2, alpha: 1)
}
}
然后更新我的控制代码:
extension MyControl {
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
if #available(iOS 13.0, *) {
if traitCollection.hasDifferentColorAppearance(comparedTo: previousTraitCollection) {
backgroundColor = traitCollection.userInterfaceStyle == .dark ?
.myControlBackgroundDark : .myControlBackgroundLight
}
}
}
}
这似乎可行,但是很笨拙,我碰巧使用的其他任何地方都myControlBackground
需要添加相同的代码。
是否有更好的解决方案来让我的自定义颜色和控件同时支持明暗模式?
1> rmaddy..:
事实证明,使用新的UIColor init(dynamicProvider:)
初始化程序确实很容易。
将自定义颜色更新为:
extension UIColor {
static var myControlBackground: UIColor {
if #available(iOS 13.0, *) {
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)
}
} else {
// Same old color used for iOS 12 and earlier
return UIColor(red: 0.3, green: 0.4, blue: 0.5, alpha: 1)
}
}
}
而已。无需定义两个单独的静态变量。控件类不需要对原始代码进行任何更改。无需覆盖traitCollectionDidChange
或其他任何内容。
这样做的好处是,您可以在“设置”应用中更改模式后立即在应用切换器中看到颜色更改。当然,当您返回应用程序时,颜色会自动更新。
关于支持明暗模式的相关说明-尽可能使用UIColor提供的多种颜色。请参阅“ UI元素”和“ 标准颜色 ”中可用的动态颜色。当您需要自己的应用特定颜色来支持亮和暗模式时,请以此答案中的代码为例。
在Objective-C中,您可以使用以下方法定义自己的动态颜色:
UIColor + MyApp.h:
@interface UIColor (MyApp)
@property (class, nonatomic, readonly) UIColor *myControlBackgroundColor;
@end
UIColor + MyApp.m:
+ (UIColor *)myControlBackgroundColor {
if (@available(iOS 13.0, *)) {
return [UIColor colorWithDynamicProvider:^UIColor * _Nonnull(UITraitCollection * _Nonnull traits) {
return traits.userInterfaceStyle == UIUserInterfaceStyleDark ?
[self colorWithRed:0.5 green:0.4 blue:0.2 alpha:1.0] :
[self colorWithRed:0.3 green:0.4 blue:0.5 alpha:1.0];
}];
} else {
return [self colorWithRed:0.3 green:0.4 blue:0.5 alpha:1.0];
}
}
是的,您有正确的主意!为了完整起见,还有一个选项:在资产目录中定义自定义颜色,然后使用UIColor(name :) / + [UIColor colorNamed:]获得颜色。