'How to change DatePicker's texts color in SwiftUI?
I saw this question but it doesn't work in SwiftUI.
I tried .forgroundColor
and .accentColor
but they don't change the texts' color.
Solution 1:[1]
I just simple set the accentColor and it works.
@State private var date = Date()
DatePicker("Select a date",
selection: $date, in: ...Date(),
displayedComponents: .date)
.labelsHidden()
.accentColor(.orange)
Solution 2:[2]
try this:
var body: some View {
Group {
DatePicker(selection: $selected) {
Text("Date")
}
.colorInvert()
.colorMultiply(Color.blue)
}
}
Solution 3:[3]
Using .colorInvert()
and .colorMultiply(.white)
will change the text color to white but won't work when the device is in Dark Mode. Instead, try this:
DatePicker("Date", selection: $selection)
.colorScheme(.dark) // or .light to get black text
Solution 4:[4]
you can do this to make the text appear white in light or dark mode if you use a background color
struct PickerDate: View {
@Environment(\.colorScheme) var colorScheme
@State var date: Date
var body: some View {
VStack {
DatePicker("Record Date", selection: $date, in: ...Date(), displayedComponents: .date)
.labelsHidden()
.colorMultiply(colorScheme == .dark ? .black : .white)
.colorInvert()
}
}
}
}
Solution 5:[5]
DatePicker("DatePicker", selection: self.$date, displayedComponents: .hourAndMinute)
.labelsHidden()
.colorMultiply(Color.white)
.colorInvert()
Solution 6:[6]
I use extension for customized text color for both of light mode and dark mode.
extension View {
@ViewBuilder func changeTextColor(_ color: Color) -> some View {
if UITraitCollection.current.userInterfaceStyle == .light {
self.colorInvert().colorMultiply(color)
} else {
self.colorMultiply(color)
}
}
}
and sample is as below.
DatePicker("Date", selection: $selection)
.labelsHidden()
.changeTextColor(.green)
Solution 7:[7]
I found applying this modifier to the DatePicker
to be cleaner:
Forces the color to white
.environment(\.colorScheme, .dark)
Forces the color to dark
.environment(\.colorScheme, .light)
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 | Hoang Anh Tuan |
Solution 2 | pkamb |
Solution 3 | Pranav Wadhwa |
Solution 4 | pkamb |
Solution 5 | HatsuneMiku |
Solution 6 | LinusGeffarth |
Solution 7 | tennis779 |