SwiftUI Picker item .foregroundColor() not working

Viewed 2673

I'm trying to set the color of the text within a Picker but it is not actually changing anything. The following is my code:

Picker("Theme Color", selection: $themeColor) {
    ForEach(0..<themeColors.count) { _ in
        Text("Color").foregroundColor(.blue)
    }
}.pickerStyle(SegmentedPickerStyle())

Is this just not possible in SwiftUI?

4 Answers

Well... nothing direct, but you can play with the following approach... which allows to get some interesting effects (maybe someone could be appropriate)

Demo prepared & tested with Xcode 12 / iOS 14

demo1

    Picker("Theme Color", selection: $themeColor) {
         ForEach(0..<4) { _ in
              Text("Color")
         }
    }.pickerStyle(SegmentedPickerStyle())
    .colorMultiply(.white).colorInvert()

and even

demo2

    Picker("Theme Color", selection: $themeColor) {
         ForEach(0..<4) { _ in
              Text("Color")
         }
    }.pickerStyle(SegmentedPickerStyle())
    .colorMultiply(.white).colorInvert()
    .colorMultiply(.orange).colorInvert()

I managed to change the foreground color of the picker, but it was far from good since the chosen item would not be readable. Considering my iOS 13 unfortunate experiences with segmented picker, and the fact that i couldn't change the picker's size at that time, i do think that pickers are still not customizable and just like me, you'll need to write your own picker if you want a more customized one.

In SwiftUI 2, Picker is still backed by UISegmentedControl.

Which means you can use the UISegmentedControl.appearance() modifiers:

UISegmentedControl.appearance().selectedSegmentTintColor = .systemOrange
UISegmentedControl.appearance().backgroundColor = .systemRed

I got the desired results using "setTitleTextAttributes"

UISegmentedControl.appearance().setTitleTextAttributes([.foregroundColor: UIColor.white], for: .normal)
Related