如何更改 ForEach 结构返回的元素的 属性
How to change a property of an element returned by a ForEach structure
我正在尝试这样做:
struct ContentView : View {
struct Element {
var color: Color
}
@State var array = [Element, Element, Element]
ForEach(array){ element in
Rectangle()
.foregroundColor(element.color)
.tapAction {
element.color = Color.red
}
我不能那样做,因为该元素是 let 常量。
我如何将元素设为变量以便我可以更改其属性?
*编辑以添加更多代码。
好的,你应该像这样重写你的代码:
import SwiftUI
struct ContentView : View {
struct Element {
var color: Color
}
@State private var array = [Element(color: .red), Element(color: .green), Element(color: .blue)]
var body: some View {
ForEach(0..<array.count) { i in
return Rectangle()
.foregroundColor(self.array[i].color)
.tapAction {
self.array[i].color = Color.red
}
}
}
}
我正在尝试这样做:
struct ContentView : View {
struct Element {
var color: Color
}
@State var array = [Element, Element, Element]
ForEach(array){ element in
Rectangle()
.foregroundColor(element.color)
.tapAction {
element.color = Color.red
}
我不能那样做,因为该元素是 let 常量。
我如何将元素设为变量以便我可以更改其属性?
*编辑以添加更多代码。
好的,你应该像这样重写你的代码:
import SwiftUI
struct ContentView : View {
struct Element {
var color: Color
}
@State private var array = [Element(color: .red), Element(color: .green), Element(color: .blue)]
var body: some View {
ForEach(0..<array.count) { i in
return Rectangle()
.foregroundColor(self.array[i].color)
.tapAction {
self.array[i].color = Color.red
}
}
}
}