'reverse .label in swift
I want my text to appear .white
when in normal mode and .black
when in dark mode. How do I do that? .label
only makes the text .black
in normal and .white
in dark mode but I want it the other way around.
Anyone have a solution for that?
Solution 1:[1]
let myLabelColor = UIColor(dynamicProvider: { $0.userInterfaceStyle == .dark ? .black : .white })
Since iOS 13, UIColor
has an init(dynamicProvider:)
Creates a color object that uses the specified block to generate its color data dynamically.
? https://developer.apple.com/documentation/uikit/uicolor/3238041-init
If you will be creating a lot of dynamic colors, you might want to make a convenience init—that saves you the typing, and your intention is more clear to the reader:
extension UIColor {
/// Creates a color object that responds to `userInterfaceStyle` trait changes.
public convenience init(light: UIColor, dark: UIColor) {
guard #available(iOS 13.0, *) else { self.init(cgColor: light.cgColor); return }
self.init(dynamicProvider: { $0.userInterfaceStyle == .dark ? dark : light })
}
}
Usage: let myLabelColor = UIColor(light: .white, dark: .black)
(Note that you can use any other trait from the provided trait collection. For example, you could return a different color if the size class changes)
Solution 2:[2]
In my assets I created a new "Color Set". For chose white for "Any Appearance" and black for "Dark". Then I gave this Image Set a name and called it like so:
text.textColor = UIColor(named: "ImageSet1")
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | PDK |
Solution 2 | JuFa512 |