将嵌套数组元素结果传递到 @Binding

Passing a nested array element result into a @Binding

我的标题可能很糟糕。这是难以命名的问题之一。

extension Color {
  static let availableForSelectionColors : [Color] = [.red,.blue,.green,.yellow]
}

我有意见

    struct myView: View {
            
            @Binding var bgColor : Color
    
               var body: some View {
               
                        VStack { 
                             ...
                         }.background(bgColor)

 }
}

我在 ForEach 循环中创建实例并设置背景颜色。

struct myOtherView : View {

 @State private var storedColors : [Int] = UserDefaults.standard.value(forKey:"key") as? [Int] ?? [0,1,3,1]
 @State private var bgColor = Color.red

 ForEach((0..<100), id: \.self) { index in
    myView(bgColor: $bgColor)
   }
 }

但是我想根据 ForEach 循环中的 storedColors 索引使用 availableForSelectionColors 设置颜色。即

...
ForEach((0..<100), id: \.self) { index in
        myView(bgColor: Color.availableForSelectionColors[storedColors[index %4]])
       }
     }

但不能,因为 Color.availableForSelectionColors[storedColors[index %4]] 不是 @Binding

然后如何制作 Color.availableForSelectionColors[storedColors[index %4]] @Binding 这样我就可以传入创建 myView。我使用了绑定,因为用户可以在模式 sheet 中更改 UserDefaults.standard.value(forKey:"key") 中的数组,这应该反映在 myView

您可以根据每个索引自己创建一个Binding。它看起来像这样(如果我正确理解你想要做什么):


func colorBinding(for index: Int) -> Binding<Color> {
   .init(
      get: { Color.availableForSelectionColors[storedColors[index]] },
      set: { storedColors[index] = Color.availableForSelectionColors
                                        .firstIndex(of: [=10=])!}
   )
}

这个函数 return 是一个 Binding<Color>,绑定绑定到 storedColors 数组中的指定元素,除了它在 ColorInt Color.availableForSelectionColors 数组中的索引。

所以,可以直接使用函数的return值作为参数给myView:

ForEach((0..<100), id: \.self) { index in
   myView(bgColor: colorBinding(for: index % 4))
}

! 用作简化,因为我假设唯一可以使用的颜色是 Color.availableForSelectionColors 数组中的颜色;显然,如果使用不同的颜色,它会被压碎。