我正在寻找一种解决此问题的方法。可能吗?
对于单个项目没有问题。所选项目将为白色,其余为我自己的颜色“ listTextColor”。但是,是否有可能以类似的方式将选择并保存在“ selectedItems”数组中的元素显示为白色,其余的显示为不同的颜色?
示例代码:
@State var recordArray: Array = arrayRecords
@State var selectedItems: Array = []
@State var selections: String?
List() {
ForEach(self.recordArray, id: \.self) { record in
Text(record)
.onTapGesture {
self.selections = record
self.selectedItems.append(record)
}
.foregroundColor(self.selections == record ? Color(.white) : Color(self.listTextColor2))
}
}
答案 0 :(得分:0)
最好的选择是使用视图模型而不是纯字符串,并在其中使用标志为行着色。
struct ContentView: View {
@State var recordArray: [RecordItem]
var body: some View {
List() {
ForEach(0..<self.recordArray.count, id: \.self) { i in
VStack {
Text(self.recordArray[i].title)
}
.border(Color.black)
.onTapGesture {
self.recordArray[i].isSelected.toggle()
self.recordArray[i] = self.recordArray[i]
}
.foregroundColor(self.recordArray[i].isSelected ? Color(.red) : Color(.green))
}
}
}
}
class RecordItem {
var title = ""
var isSelected = false
}
答案 1 :(得分:0)
我找到了这个问题的答案。
@State var recordArray: Array = arrayRecords
@State var selectedItems: Array = []
@State var selections: String?
var body: some View {
List() {
ForEach(self.recordArray, id: \.self) { record in
Text(record)
.onTapGesture {
if self.selectedItems.first(where: { $0 as! String == record } ) != nil {
self.selectedItems.removeAll(where: { $0 as! String == record } )
} else {
self.selectedItems.append(record)
}
}
.foregroundColor((self.selectedItems.first(where: { $0 as! String == record } ) != nil) ? Color(.white) : Color(self.listTextColor2))
}
}
}