UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

HELP: Segmented Picker Tint Color

Forums > SwiftUI

Does anyone know how to achieve this? I have four colors of red, green, yellow, and blue and I want my selected segment to have a background/tint color that is indicative of the color name. This is my code:

let objectColors = Color.allCases
@State private var selectedColorIndex = 0

//declared inside body view
Picker("Colors", selection: $selectedColorIndex){
        ForEach(0..<objectColors.count){ index in
            Text(self.objectColors[index].rawValue).tag(index)
        }
    }.pickerStyle(SegmentedPickerStyle())
    .padding(10)
    .onAppear {
        UISegmentedControl.appearance().selectedSegmentTintColor = UIColor.generateUIColor(colorIndex: selectedColorIndex)        
    }

This is the list I'm pulling from

enum Color: String, CaseIterable{
    case red, yellow, green, blue
}

I've tried using onChange or onReceive (and Combine's 'Just()' for subview) instead of onAppear but they crash on playgrounds and don't work on Xcode. I also saw a WWDC video on UIAction that I think will work great for updating view changes but I have no idea how to translate it. Does anyone one have any suggestions or help, please? Thanks

2      

The way I have done it is

enum Colors: String, CaseIterable{
    case red, yellow, green, blue

    func displayColor() -> String {
        self.rawValue.capitalized
    }
}
struct ContentView: View {
    @State private var selectedColor = Colors.red

    var body: some View {
        Picker(selection: $selectedColor, label: Text("Colors")) {
            ForEach(Colors.allCases, id: \.self) { color in
                Text(color.displayColor())
            }
        }
        .padding()
        .colorMultiply(color(selectedColor))
        .pickerStyle(SegmentedPickerStyle())
    }

    func color(_ selected: Colors) -> Color {
        switch selected {
        case .red:
            return .red
        case .yellow:
            return .yellow
        case .green:
            return .green
        case .blue:
            return .blue
        }
    }
}

5      

Hacking with Swift is sponsored by Essential Developer

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until April 28th.

Click to save your free spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.