Picker has a number of limitations about what it can display.
The following example code shows how to display the listOfColorsAvailable
but only with the .wheel
and .inline
style picker.
Note the selection teamColor
, must match the type of the tag()
of the picker elements.
struct ContentView: View {
var body: some View {
TeamColorPicker()
}
}
struct TeamColorPicker: View {
@State private var teamColor: String = "Blue" // <--- here, same type as tag()
var listOfColorsAvailable: [String] = ["Red", "Blue", "Teal", "Green", "Yellow", "Orange"]
var body: some View {
Picker("Team Color", selection: $teamColor) {
ForEach(listOfColorsAvailable, id: \.self) { colorString in
ColorSquare(color: asColor(colorString))
.tag(colorString) // <--- here, same type as teamColor
}
}
.pickerStyle(.wheel) // <--- here, .wheel, .inline
}
// for testing, can use Assets.xcassets
func asColor( _ color: String) -> Color {
switch color {
case "Red": Color.red
case "Blue": Color.blue
case "Teal": Color.teal
case "Green": Color.green
case "Yellow": Color.yellow
case "Orange": Color.orange
default: Color.black
}
}
}
struct ColorSquare: View {
var color: Color
var body: some View {
Rectangle().fill(color).frame(width: 22, height: 22)
}
}
Alternatively, using Color
directly:
struct TeamColorPicker: View {
@State private var teamColor: Color = Color.blue // <--- here, same type as tag()
let listOfColorsAvailable: [Color] = [.red, .blue, .teal, .green, .yellow, .orange]
var body: some View {
teamColor.frame(width: 22, height: 22) // <-- for testing
Picker("Team Color", selection: $teamColor) {
ForEach(listOfColorsAvailable, id: \.self) { color in
ColorSquare(color: color)
.tag(color) // <--- here, same type as teamColor
}
}
.pickerStyle(.wheel) // <--- here, .wheel, .inline
}
}
struct ColorSquare: View {
var color: Color
var body: some View {
Rectangle().fill(color).frame(width: 22, height: 22)
}
}