'Choosing a random color from an array of colors to use in a View in SwiftUI
How can I chose a random color from an array of colors when iterating on an array of names so each name will have a diffrent text foreground color ?
struct TextRow: View {
var names : [String]
var color: [Color]
var body: some View {
HStack{
ForEach(names, id: \.self){
item in
Text(item)
}
}
}
}
Solution 1:[1]
You could simply shuffle the colors array and then iterate on the names index
Example:
extension Collection {
subscript(safe index: Index) -> Element? {
return indices.contains(index) ? self[index] : nil
}
}
struct ContentView: View {
var names : [String] = ["1", "2" ,"3","4","5","6","7","8","9"]
var colors: [Color] = [.red, .gray, .green, .yellow, .blue].shuffled()
var body: some View {
HStack{
ForEach(Array(names.enumerated()), id: \.offset) { index, element in
Text(element)
.background(colors[safe: index] ?? colors[safe: index - colors.count])
}
}
}
}
I added the safe collection extension in case names and colors have a different count
Solution 2:[2]
This did the job for me:
// ... omitted
var body: some View {
let colors: [Color] = [.green, .red, .primaryColor, .orange, .blue, .gray]
ScrollView {
Image(systemName: name.prefix(1).lowercased() + ".circle.fill")
.resizable()
.frame(width: 40, height: 40)
.foregroundColor(colors.randomElement())
}
/// ... omitted**strong text**
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 | Ludyem |
| Solution 2 | Edi |
