ios - 从一组颜色中选择一种随机颜色以在 SwiftUI 的视图中使用
问题描述
在对名称数组进行迭代时,如何从颜色数组中选择一种随机颜色,以便每个名称都有不同的文本前景色?
struct TextRow: View {
var names : [String]
var color: [Color]
var body: some View {
HStack{
ForEach(names, id: \.self){
item in
Text(item)
}
}
}
}
解决方案
您可以简单地打乱颜色数组,然后迭代名称索引
例子:
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])
}
}
}
}
我添加了安全集合扩展,以防名称和颜色有不同的计数
推荐阅读
- mongodb - 无法连接到 mongodb 副本集 Google Compute Engine
- c++ - C++20:从自定义迭代器制作反向迭代器失败
- kotlin - 使用 Jasync 时从 JOOQ 查询中提取数据
- c - 程序返回错误值
- reactjs - 如何在反应中默认选择所有单选按钮
- python - 将数据帧上传到 s3 python
- haskell - 为什么这个 Haskell 函数的返回值与定义的函数的返回值不同?
- android - 使用带有语言环境的 DateFormat 会导致 FormatException: Trying to read yyyy from 2020-08-07 15:00 at position 0
- javascript - 如何仅在 yii2 中选择后渲染视图
- ios - 父对象的核心数据列表关系