Pjaks
Pjaks

Reputation: 411

Can you access Picker elements during runtime and change their color

I want to change the color of the current selected Element of the Picker. Is this possible? This is my code.

Picker("Select a Project", selection: $selectedProjectString){
            ForEach(projects, id: \.self) {
                Text($0).lineLimit(1).frame(height:120)
            }
        }.foregroundColor(Color.white)
            .frame(height: 120)

The element that matches selectedProjectString should be a different color than all the others. Or is it possible to access specific elements like with an index or something?

Upvotes: 2

Views: 69

Answers (1)

Pjaks
Pjaks

Reputation: 411

I came up with this solution:

Picker("Select a Project", selection: $selectedProjectString){
            ForEach(projects, id: \.self) {
                if (startedProject == $0) {
                    Text($0).lineLimit(1).frame(height:120).foregroundColor(Color.red)
                } else {
                    Text($0).lineLimit(1).frame(height:120)
                }
                
            }
        }.foregroundColor(Color.white)
            .frame(height: 120)

I check if the selected element equals some value and if, I change the style of the Text object it belongs. Because i change the value of the variable, the view gets reloaded and it refreshes my picker. Now the selected element has color.

Upvotes: 1

Related Questions