Let's say I have a custom color in my app:
extension UIColor {
static var myControlBackground: UIColor {
return UIColor(red: 0.3, green: 0.4, blue: 0.5, alpha: 1)
}
}
I use this in a custom control (and other places) as the control's background:
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
}
With iOS 13, I wish to have my custom control support both light and dark mode.
One solution is to override traitCollectionDidChange
and see if the color has changed and then update my background as needed. I also need to provide both a light and dark color.
So I update my custom colors:
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)
}
}
And I update my control code:
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
}
}
}
}
This seems to work but it's clunky and anywhere else I happen to use myControlBackground
needs to have the same code added.
Is there a better solution to having my custom color and control support both light and dark mode?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…