首页 > 解决方案 > 从一组颜色中选择一种随机颜色以在 SwiftUI 的视图中使用

问题描述

在对名称数组进行迭代时,如何从颜色数组中选择一种随机颜色,以便每个名称都有不同的文本前景色?

struct TextRow: View {
var names : [String]
var color: [Color]
var body: some View {
      HStack{
         
           ForEach(names, id: \.self){
           item in
                
               Text(item)
           }
        }
   }
}

标签: iosswiftui

解决方案


您可以简单地打乱颜色数组,然后迭代名称索引

例子:

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])
            }
        }
    }
}

我添加了安全集合扩展,以防名称和颜色有不同的计数


推荐阅读